为了账号安全,请及时绑定邮箱和手机立即绑定

无法在 FirebaseRecyclerView 中显示子节点数据。

无法在 FirebaseRecyclerView 中显示子节点数据。

HUWWW 2022-05-25 10:47:20
我需要显示一个列表(来自 Firebase 实时数据库的数据绑定到 aRecyclerView中),它位于根目录 -> 历史记录 -> UID -> 位置、日期。我目前只能显示历史记录下的所有数据。当我尝试将 History 节点过滤到 UID 的子节点时会出现问题,并且它会给出以下错误:com.google.firebase.database.DatabaseException:无法将 java.lang.String 类型的对象转换为 com.example.ModelHistory 类型这是我的 ModelHistory.class:public class ModelHistory {String location, date;// Constructorpublic ModelHistory() {}public String getLocation() {    return location;}// It shows a warning here that setLocation is never usedpublic void setLocation(String location) {    this.location = location;}public String getDate() {    return date;}public void setDate(String date) {    this.date = date;}}这是我的RecentHistory.java:public class RecentHistory extends AppCompatActivity {    RecyclerView mRecyclerView;    FirebaseDatabase mFirebaseDatabase;    DatabaseReference mRef, uidRef;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_recent_history);        // Set ActionBar        ActionBar actionBar = getSupportActionBar();        actionBar.setTitle("History");        mRecyclerView = findViewById(R.id.rvHistory);        mRecyclerView.setHasFixedSize(true);        // Set Layout        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));        // Send Query to Firebase Db        mFirebaseDatabase = FirebaseDatabase.getInstance();        String currentuser = FirebaseAuth.getInstance().getCurrentUser().getUid();        mRef = mFirebaseDatabase.getReference("History");        uidRef = mRef.child(currentuser);        Log.d("TAG", uidRef.toString());    }如果需要xml,请告诉我,我将编辑帖子。
查看完整描述

1 回答

?
偶然的你

TA贡献1841条经验 获得超3个赞

您收到以下错误:


com.google.firebase.database.DatabaseException:无法将 java.lang.String 类型的对象转换为 com.example.ModelHistory 类型


因为这是将 传递uidRef给FirebaseRecyclerAdapter构造函数时的正确行为。


我目前只能显示历史记录下的所有数据。


发生这种情况是因为您的适配器被定义为FirebaseRecyclerAdapter<ModelHistory, ViewHolder>,这意味着它应该加载ModelHistory它在您的mRef引用下找到的所有类型的对象,这实际上是正确的。该引用下存在的所有对象都是类型ModelHistory。


当我尝试将History节点过滤到UID的子节点时出现问题


您不能简单地更改引用并期望以这种方式过滤结果,因为您的适配器仍然是类型ModelHistory而不是字符串类型。因此,当使用uidRef引用时,这意味着您正在尝试加载ModelHistory该引用下的所有类型的对象,这些对象显然不会退出。仅root -> History -> UID存在 String ( location and date) 类型的属性,这就是您收到该错误的原因。


如果您想过滤该数据,您应该创建一个可能如下所示的查询:


DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();

DatabaseReference hisotryRef = rootRef.child("History");

Query query = hisotryRef.orderByChild("location").equalTo("Test");

并且您的结果RecyclerView将只有一项,在这种情况下是最后一项,即具有 location 属性的一项Test。


除此之外,您使用的是旧版本的Firebase-UI 库。我建议您更新到最新版本。


查看完整回答
反对 回复 2022-05-25
  • 1 回答
  • 0 关注
  • 124 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号