I am trying to retrieve Messages/child
sorted on the base of time
. I have access to Messages/child
. I am unable to find any useful solution. Please help me figure this out.
My current code is:
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());
}
you can do this way :-
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) {
}
});
Try this..
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
}
}
}
});
As far as I can see you have a data structure:
Messages: {
uid1: {
uid2: {
messageId1: ...
messageId2: ...
messageId3: ...
}
}
}
You attach a ChildEventListener
to /Messages/uid1
, which means that your onChildAdded
gets called for user second-level UID from your JSON. To get to the individual messages, you still need to loop over the child nodes of the 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));
}
}
A few things to note:
DataSnapshot
to get to the individual messages. "20190513T073306"
or a timestamp such as 1557758003677
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.