我的 Firebase 实时数据库是这样的:
{Singer :
Billie Eilish :
01 :
songType : "type01"
songName : "bad guy"
02 :
songType : "type02"
songName : "bury a friend"
Lauv :
01 :
songType : "type01"
songName : "I Like Me Better"
02 :
songType : "type03"
songName : "lonely"
Anne Marie :
01 :
songType : "type02"
songName : "2002"
...
...
...
}
如果我想得到“type01”的所有歌曲,我该怎么办?这是我的适配器类,它在 MainActivity 的 recyclerView 中显示数据。
适配器类:
public class MyAdapter extends Recycler.Adapter {
...
@Override
public void onBindViewHolder(@Nonnull ViewHolder holder, int i) {
...
Query query = FirebaseDatabase.getInstance().getReference().child("Singer");
options = new FirebaseRecyclerOptions.Builder<ItemModel>().setQuery(query, new SnapshotParser<ItemModel>() {
@NonNull
@Override
public ItemModel parseSnapshot(@NonNull DataSnapshot snapshot) {
if (snapshot.child("songType").getValue().toString().equals("type01") {
String song = snapshot.child("songName").getValue().toString();
return new ItemModel(song);
}
return null;
}
}).build();
recyclerAdapter = new AnotherAdapter(options);
recyclerAdapter.startListening();
}
我认为这在查询中很奇怪。它只称 child 为“歌手”。我想给所有的 child 打电话,得到什么 songType 是“type01”。 AnotherAdapter 只是扩展 FirebaseReyclcerAdapter 并在其 AnotherViewHolder 中设置文本。
最佳答案
你为什么不直接使用仅包含songType : type01 的获取数据试试这个
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("Singer").orderByChild("songType").equalTo("type01");
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot issue : dataSnapshot.getChildren()) {
//set featched value to recyclerview
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
关于android - 如何使用 Android 获取 Firebase 数据库中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58055870/