我有以下数据结构
"messages" : {
"Johnny_peter" : {
"-KsjbzGUO90vejwHpzqx" : {
"message" : "how are u doing",
"user" : "peter",
"userName" : "peter"
}
},
"guy_steve" : {
"-Ksj5vkO5H4qeleFqojh" : {
"message" : "merci",
"user" : "steve",
"userName" : "steve"
}
我正在使用关注代码来检索用户名
的值 mDatabase = FirebaseDatabase.getInstance().getReference(Constants.DATABASE_PATH_CHATLISTS);
//adding an event listener to fetch values
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
//dismissing the progress dialog
progressDialog.dismiss();
//iterating through all the values in database
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
ChatList chatlist= postSnapshot.getValue(ChatList.class);
chatLists.add(chatlist);
}
//creating adapter
adapter = new MyAdapterChatList(getApplicationContext(), chatLists);
//adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
问题:使用上面的代码,我无法检索userName的值 任何帮助都值得赞赏
答案 0 :(得分:0)
要实现此目的,请使用以下代码:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference messagesRef = rootRef.child("messages");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
for(DataSnapshot dSnapshot : ds.getChildren()) {
String userName = dSnapshot.child("userName").getValue(String.class);
Log.d("TAG", userName);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
messagesRef.addListenerForSingleValueEvent(eventListener);
您的输出将是:
peter
steve