Get last node in Firebase database Android

后端 未结 4 2038
醉梦人生
醉梦人生 2020-12-25 08:21

I want to get item in the last node added in firebase database from my Android. You can see on the image below i\'m not sure how to get the specific node, because unique key

相关标签:
4条回答
  • 2020-12-25 08:51

    I prefer to write and retrieve data through objects. MyObject is POJO.

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot data : dataSnapshot.getChildren()) {
            MyObject myObject = data.getValue(MyObject.class);
            Log.i(TAG, data.getKey() + " = " + myObject.toString());
        }
    }
    
    0 讨论(0)
  • 2020-12-25 09:03

    This might work:

    DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("mp");
    Query query = db.orderByKey().limitToLast(1);
    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot child: dataSnapshot.getChildren()) {
                Log.d("User key", child.getKey());
                Log.d("User val", child.child("message").getValue().toString());
            } 
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {
            // TODO: Handle errors.
        }
    });
    
    0 讨论(0)
  • 2020-12-25 09:04

    Try this:

    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
    Query lastQuery = databaseReference.child("mp").orderByKey().limitToLast(1);
    lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String message = dataSnapshot.child("message").getValue().toString();
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {
            // Handle possible errors.
        }
    });
    

    Hope this helps!

    0 讨论(0)
  • 2020-12-25 09:09

    console.log('last messages', messages[messages.length-1]);

    0 讨论(0)
提交回复
热议问题