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

无法从Firestore文档引用获取数据,返回值始终为null求助

解决Firebase Firestore获取数据返回null的问题

嗨,我看了你的代码,问题出在Firestore的异步调用特性上!

你写的Gettingdata()方法里,firebaseFirestore.collection(...).get()是个异步操作——它会在后台线程去请求数据,而你的方法会立刻返回初始值null,等onSuccess或者onFailure回调执行的时候,Gettingdata()早就跑完了,所以你拿到的自然是null。

下面给你修正后的代码,核心思路是把UI更新逻辑放到异步回调里,而不是试图从方法里返回数据:

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;

public class MainActivity extends AppCompatActivity {
    FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
    TextView txt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt = findViewById(R.id.textView);
        // 直接调用获取数据的方法,不用返回值
        fetchUserData();
    }

    private void fetchUserData() {
        firebaseFirestore.collection("Users").document("NewDocument")
                .get()
                .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                    @Override
                    public void onSuccess(DocumentSnapshot documentSnapshot) {
                        // 用exists()判断文档是否存在,比直接判null更准确
                        if (documentSnapshot.exists()) { 
                            String email = documentSnapshot.getString("email");
                            // 注意points的类型,如果是整数用getLong,浮点数用getDouble
                            long points = documentSnapshot.getLong("points"); 
                            txt.setText("Email: " + email + "\nPoints: " + points);
                        } else {
                            txt.setText("文档不存在");
                            Log.d("Tag", "文档不存在");
                        }
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        txt.setText("获取数据失败");
                        Log.d("Tag", "失败原因: " + e.getMessage());
                        Toast.makeText(MainActivity.this, "获取数据失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }
}

另外还有几个需要检查的点,避免踩坑:

  • 确认你的Firebase项目配置正确,google-services.json已经放在app目录下
  • 检查Firestore的安全规则,开发阶段可以暂时放开权限(上线后一定要改回严格规则):
    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if true;
        }
      }
    }
    
  • 确认集合名Users、文档IDNewDocument、字段名email和points的拼写和大小写完全一致(Firestore是大小写敏感的)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:18:42