猿问

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

我需要显示一个列表(来自 Firebase 实时数据库的数据绑定到 aRecyclerView中),它位于根目录 -> 历史记录 -> UID -> 位置、日期。我目前只能显示历史记录下的所有数据。当我尝试将 History 节点过滤到 UID 的子节点时会出现问题,并且它会给出以下错误:


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


这是我的 ModelHistory.class:


public class ModelHistory {


String location, date;


// Constructor

public ModelHistory() {


}


public String getLocation() {

    return location;

}

// It shows a warning here that setLocation is never used

public 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,请告诉我,我将编辑帖子。


HUWWW
浏览 125回答 1
1回答

偶然的你

您收到以下错误: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 库。我建议您更新到最新版本。
随时随地看视频慕课网APP

相关分类

Java
我要回答