我正在尝试检索基于Messages/child
排序的time
。我可以访问Messages/child
。我找不到任何有用的解决方案。请帮我解决这个问题。
我当前的代码是:
FirebaseDatabase.getInstance()
.getReference()
.child("Messages")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable, String s) {
Log.d("children",dataSnapshot.getKey());
users_list.add(dataSnapshot.getKey());
}
答案 0 :(得分:1)
据我所知,您有一个数据结构:
Messages: {
uid1: {
uid2: {
messageId1: ...
messageId2: ...
messageId3: ...
}
}
}
您将ChildEventListener
附加到/Messages/uid1
上,这意味着您的onChildAdded
被从JSON调用为用户二级UID。要获取各个消息,您仍然需要遍历DataSnapshot
的子节点:
FirebaseDatabase.getInstance()
.getReference()
.child("Messages")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable, String s) {
for (DataSnapshot messageSnapshot: dataSnapshot.getChildren()) {
Log.d("message key: ", messageSnapshot.getKey());
Log.d("message time: ", messageSnapshot.child("time").getValue(String.class));
}
}
一些注意事项:
DataSnapshot
的子级上循环以获取各个消息。"20190513T073306"
或使用时间戳记例如1557758003677
。答案 1 :(得分:0)
您可以这样:-
mChatReference = FirebaseDatabase.getInstance().getReference("Messages")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
Query query = mChatReference.orderByChild("time");
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Log.d("children",dataSnapshot.getKey());
users_list.add(dataSnapshot.getKey());
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
答案 2 :(得分:0)
尝试一下。
DocumentReference docRef = FirebaseFirestore.getInstance().collection(YOUR_COLLECTION).document(FirebaseAuth.getInstance().getCurrentUser().getUid());
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
if (document.contains("message")) {
String message=document.get("message").toString());
}
//add other information to your user_list
}
}
}
});