我有Firebase数据库的结构:
DB
- 用户
- UID
---- UsersMessages
------- UNIQUEID
-------文字信息
------- typeOfMessage
代码
Marshal.GetDelegateForFunctionPointer(methodAddress, delegateType);
但我需要从用户那里获取所有消息。我怎么能得到那些?我如何只搜索孩子"消息"没有"用户"并采取"消息文本值"。我可以吗?如何将此信息添加到ListView?
答案 0 :(得分:0)
要获取所有用户的所有消息,请使用以下代码:
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
String uid = firebaseUser.getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference messagesRef = rootRef.child(USERS_CHILD).child(uid).child("Messages");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String messageText = ds.child("MessageText").getValue(String.class);
Log.d("TAG", messageText);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
messagesRef.addListenerForSingleValueEvent(eventListener);
您的输出将是:
asasddd
asasddd
asasddd
要获取用户的消息,请使用以下代码:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userKey = ds.getKey();
DatabaseReference messagesRef = usersRef.child(userKey).child("Messages");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
String messageText = dSnapshot.child("MessageText").getValue(String.class);
Log.d("TAG", messageText);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
messagesRef.addListenerForSingleValueEvent(eventListener);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(valueEventListener);
答案 1 :(得分:0)
首先,您需要使用以下内容获取DatabaseRefence
:
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User/...pathToMessage/Messages");
然后您可以使用回调加载所有邮件:
databaseReference.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// callback to get all your messages from user.
if (dataSnapshot == null) return;
MessageModel mess = dataSnapshot.getValue(MessageModel.class);
// display message here
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});