Firestore RecyclerView变量为空:从Firestore取值后退出函数时值为null
解决RecyclerView中Firestore异步回调导致数据为空的问题
问题根源
Firestore的get()方法是异步执行的,addOnCompleteListener内的回调代码会在数据库请求完成后才触发;而你原本的holder.txtFullname.setText(fullNameBeneficiary)是同步执行的,此时回调还未拿到数据,fullNameBeneficiary自然为null。另外你拼接姓名的逻辑位置错误,即便回调执行,也可能因文档不存在导致变量为空。
修正后的代码
@Override protected void onBindViewHolder(@NonNull ViewDonationHolder holder, int position, @NonNull DonationsClass model) { beneficiaryUID = model.getBeneficiaryUid(); DocumentReference docRef = db.collection("beneficiaries").document(beneficiaryUID); 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 beneficiaryFirstName = document.getString("firstName"); String beneficiaryLastName = document.getString("lastName"); // 拿到数据后直接拼接并更新UI String fullNameBeneficiary = beneficiaryFirstName + " - " + beneficiaryLastName; holder.txtFullname.setText(fullNameBeneficiary); Log.e("fullName", fullNameBeneficiary); } else { // 文档不存在时显示默认文本 holder.txtFullname.setText("未知受益人"); } } else { // 请求失败时的提示 holder.txtFullname.setText("获取信息失败"); } } }); // 本地已有数据直接设置 holder.txtDate.setText(model.getDate()); holder.txtType.setText(model.getType()); holder.txtQuantity.setText(model.getQuantity()); holder.txtDescription.setText(model.getDescription()); }
关键修改点
- 将姓名拼接和
setText操作移到回调内部,确保只有拿到Firestore数据后才更新UI - 把姓名变量改为回调内的局部变量,避免外部变量的线程安全问题
- 补充了文档不存在、请求失败的异常处理,避免UI空白
额外优化建议
- 若需要实时同步受益人信息,可使用
addSnapshotListener替代get(),数据更新时RecyclerView会自动刷新 - 可添加加载状态(比如请求开始时显示"加载中"),提升用户体验
内容的提问来源于stack exchange,提问作者Joaquin Poggio
相关产品推荐
相关产品推荐

