Firestore文档引用返回Null字符串无报错,无法读取用户数据求助
问题解决方案
首要原因:字段名大小写不匹配
你的Firestore用户文档中,名字字段是小写的name,但代码里调用documentSnapshot.getString("Name")时用了首字母大写的Name。Firestore的字段名严格区分大小写,这直接导致读取不到值,返回null。
修改代码中的字段名即可解决:
txtwelcome.setText("Welcome "+documentSnapshot.getString("name"));
额外排查步骤(若修改后仍异常)
验证用户ID正确性:
打印userID确认是否与Firestore中的文档ID一致:Log.d("Homepage", "当前用户ID: " + userID);如果ID不匹配,检查
fAuth.getUid()是否在用户登录状态下调用(确保用户已完成登录流程)。检查Firestore安全规则:
确保当前登录用户有读取users集合的权限,测试阶段可临时设置规则:rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /users/{userId} { allow read, write: if request.auth != null && request.auth.uid == userId; } } }添加文档存在性判断:
在读取数据前先确认文档存在,避免空指针或异常:@Override public void onSuccess(DocumentSnapshot documentSnapshot) { if (documentSnapshot.exists()) { String userName = documentSnapshot.getString("name"); txtwelcome.setText("Welcome " + (userName != null ? userName : "Guest")); } else { Toast.makeText(Homepage.this, "未找到用户文档", Toast.LENGTH_LONG).show(); } }
内容的提问来源于stack exchange,提问作者Hamza Ateya
相关产品推荐
相关产品推荐

