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

Android调用Firestore报Unable to start activity错误,RecyclerView无数据显示

错误原因

你遇到的空指针异常是代码执行顺序错误导致的:调用firestore.collection("notes")方法时,firestore对象还没有完成初始化,此时它的值为null,调用方法就会触发空指针崩溃。

修复步骤

  1. 调整初始化顺序,将firestore = FirebaseFirestore.getInstance()代码移到所有调用firestore方法的逻辑之前。
  2. 你当前的查询逻辑和你给出的数据库结构不匹配,现有代码直接查询根集合notes只能拿到以用户uid为文档ID的上层文档,无法获取到实际存储笔记的myNotes子集合数据,需要先获取当前登录用户的uid,再查询对应的子集合路径。

修正后的onCreate参考代码

{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home_page);

    binding = ActivityHomePageBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());

    // 先初始化firestore对象
    firestore = FirebaseFirestore.getInstance();
    // 获取当前登录用户的uid,需要确保用户已经完成Firebase登录
    FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
    if (currentUser == null) {
        // 可以在这里处理未登录的跳转逻辑
        return;
    }
    String uid = currentUser.getUid();

    datalist=new ArrayList<>();
    recyclerView = findViewById(R.id.recyclerview);
    recyclerView.setHasFixedSize(true);
    layoutManager2 = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(layoutManager2);
    recyclerView.setAdapter(adapter);

    // 调整查询路径匹配你的数据库结构
    firestore.collection("notes").document(uid).collection("myNotes")
        .get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
            @Override
            public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                List<DocumentSnapshot> list=queryDocumentSnapshots.getDocuments();
                for(DocumentSnapshot d:list)
                {
                    firebaseModel obj=d.toObject(firebaseModel.class);
                    datalist.add(obj);
                }
                adapter.notifyDataSetChanged();
            }
        });

    addNotes = findViewById(R.id.add_button);

    Objects.requireNonNull(getSupportActionBar()).setTitle("Notes");

    addNotes.setOnClickListener(v -> startActivity(new Intent(HomePage.this,addNotes.class)));
}

额外注意事项

  • 需要确保你的应用已经完成Firebase Auth的登录逻辑,否则currentUser会为null,无法正常查询数据
  • 可以给Firestore的查询操作添加addOnFailureListener捕获异常,方便后续排查其他问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 00:36:04