Firebase Firestore日期保存成功但编辑页无法读取日期数据如何解决
问题根源
你出现该问题的核心原因是Firestore生日字段名前后不统一,且编辑页面的数据源依赖Intent传参容易出错:
- 注册保存逻辑中,你往Firestore写入的生日字段是
bday - 编辑页保存更新逻辑中,你写入的生日字段是
singup_bday,二者对应两个完全独立的字段 - 编辑页当前从Intent取
singup_bday的值,若跳转编辑页的上游页面没有正确从Firestore读取bday字段并传入Intent,自然读取不到值
修复方案
1. 统一字段名
先修改EditProfile类的保存更新逻辑,将生日字段名和注册逻辑保持一致,修改代码如下:
// 找到saveBtn点击事件里的Map赋值部分,把字段名改为bday edited.put("bday",profileBday.getText().toString());
2. 优化编辑页数据获取逻辑(推荐)
不要依赖Intent传递用户数据,直接在编辑页主动查询Firestore获取最新数据,避免上游传参错误,在EditProfile的onCreate方法中加入以下代码:
// 在初始化fStore、user之后加入这段代码 fStore.collection("users").document(user.getUid()).get() .addOnSuccessListener(documentSnapshot -> { if (documentSnapshot.exists()) { // 读取Firestore中存储的生日字段 String bday = documentSnapshot.getString("bday"); profileBday.setText(bday); // 其他字段也可以直接从这里读取,无需依赖Intent传参 profileFullName.setText(documentSnapshot.getString("fName")); profileEmail.setText(documentSnapshot.getString("email")); profilePhone.setText(documentSnapshot.getString("phone")); profileAddre.setText(documentSnapshot.getString("addre")); } }) .addOnFailureListener(e -> { Toast.makeText(EditProfile.this, "加载数据失败:" + e.getMessage(), Toast.LENGTH_SHORT).show(); });
加入后可以删除原来从Intent拿数据赋值的相关代码,避免覆盖查询结果。
3. 若仍要使用Intent传参
检查跳转至EditProfile的上游页面代码,确保从Firestore读取bday字段后,传入Intent的key和EditProfile中取值的key完全一致:
// 上游页面跳转代码示例 Intent editIntent = new Intent(CurrentActivity.this, EditProfile.class); // 其他参数不变,生日字段要读Firestore的bday,key设为singup_bday editIntent.putExtra("singup_bday", documentSnapshot.getString("bday")); startActivity(editIntent);
内容的提问来源于stack exchange,提问作者kenz
相关产品推荐
相关产品推荐

