Firebase gets last id - limitToLast not working - android

I am trying to get the last identifier of my node messages, but it does not get the last. For example, my last identifier is 12, but it always returns the identifier of element 10. My code looks like this:

final Query query = firebase.orderByChild("messageId").limitToLast(1); query.addListenerForSingleValueEvent(new ValueEventListener() { public void onDataChange(DataSnapshot dataSnapshot) { Log.i("MessagesFrag","snapshot: "+dataSnapshot.getValue()+""); } public void onCancelled(FirebaseError firebaseError) {} }); 

It returns something like this:

 {10={chatId=6, time=Wed Apr 13 22:20:43 EDT 2016, message=hi, user=123, messageId=10}} 

He must return:

 {12={chatId=6, time=Wed Apr 13 22:29:02 EDT 2016, message=I am fine, user=1234, messageId=12}} 

My data looks something like this:

 messages 9: chatId: "6" message: "hi" messageId: "9" time: "Wed Apr 13 22:29:02 EDT 2016" user: "123" 10: chatId: "6" message: "hello" messageId: "10" time: "Wed Apr 13 22:29:02 EDT 2016" user: "1234" 11: chatId: "6" message: "how are you?" messageId: "11" time: "Wed Apr 13 22:29:02 EDT 2016" user: "123" 12: chatId: "6" message: "I am fine" messageId: "12" time: "Wed Apr 13 22:29:02 EDT 2016" user: "1234" 

In addition to this, when I change “LimitToLast” to “LimitToFirst” (this should be the first), it does not get the first element that I have (node ​​1), it also gets node 10.

Does anyone know what the problem is?

+5
source share
1 answer

I believe that the problem is orderByChild , since messages are ordered numerically, you do not need to order them again. try the following:

  FirebaseDatabase database = FirebaseDatabase.getInstance(); // change this to your databae ref final DatabaseReference messages = database .getReference("XXXX") .child("XXXX"); // change this to your databae ref messages .limitToLast(1).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { // access last message DataSnapshot messageSnapShot= dataSnapshot.getChildren().iterator().next(); } } @Override public void onCancelled(DatabaseError databaseError) { } }); 
0
source

Source: https://habr.com/ru/post/1247091/


All Articles