You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中无法从Firestore集合获取字段值的问题

问题分析与解决方案

核心问题是Firestore数据获取为异步操作,你的代码在请求还未返回时就执行了tvMenu.setText(value),此时数据尚未获取,且代码中value变量未定义(实际应使用dbValue),导致TextView显示为空。

修正后的代码

FirebaseFirestore db = FirebaseFirestore.getInstance();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu);

    tvMenu = findViewById(R.id.tvMainMenu);
    btOpenOs = findViewById(R.id.btNewOs);

    DocumentReference docRef =
            db.collection("usuarios")
                    .document("idtest");

    docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                DocumentSnapshot document = task.getResult();
                if (document.exists()) {
                    String dbValue = document.getString("password");
                    Log.d("TAG", "DocumentSnapshot data: " + document.getData());
                    // 数据获取完成后再更新TextView
                    tvMenu.setText(dbValue);
                } else {
                    Log.d("TAG", "No such document");
                    tvMenu.setText("文档不存在");
                }
            } else {
                Log.d("TAG", "get failed with ", task.getException());
                tvMenu.setText("获取数据失败");
            }
        }
    });
}

关键说明

  • Firestore的get()方法异步执行,会在后台线程请求数据,仅当请求完成后才会触发onComplete回调。原代码在回调外部调用setText,此时dbValue未被赋值,必然显示为空。
  • 必须将更新UI的tvMenu.setText(...)代码放在onComplete回调内部,确保数据成功获取后再更新TextView。
  • 补充异常和文档不存在的处理逻辑,避免TextView持续空白,给用户明确反馈。

内容的提问来源于stack exchange,提问作者Leonardo Maito

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 15:03:50