I'm developing an app. The app must able to show the latest 10 registered user detail from real-time database. That is, It removes any user older than latest 10 users. Is there any way I can do this? Right now my app is able to access the user details stored in realtime firebase. Thanks in advance.
Asked
Active
Viewed 120 times
1 Answers
1
That sounds totally feasible. An incredibly simple way is to retrieve 11 users in your app, and then just remove the last one.
ref.orderByChild("descending_timestamp").limitToFirst(11).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
int userCount = 0;
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
if (userCount++ > 10) {
userSnapshot.getRef().remove();
} else {
// TODO: show the user in your app
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "load users", databaseError.toException());
}
});
You'll note that I order on descending_timestamp
, which is a property that you must add to the data and that allows you to sort the users in reverse chronological order. For more on this, see Firebase Data Desc Sorting in Android

Frank van Puffelen
- 565,676
- 79
- 828
- 807
-
1Can you please explain the descending timestamp property. I didn't get it properly. – Pradeep Anand Jan 10 '19 at 02:42
-
The Firebase Realtime Database can only order results in ascending order of value. Since you want the results in reverse chronological order, we need to somehow invert those results. You can either do that in client-side code, or do a trick where you store the inverted value. As an example: say that you have 5 results: `1, 2, 3, 4, 5` that you want in descending order. Since the database doesn't support that, we instead store: `-1, -2, -3, -4, -5`. When you order those (ascending), they become `-5, -4, -3, -2, -1`, which is precisely the order you wanted to begin with. I hope this makes sense. – Frank van Puffelen Jan 10 '19 at 03:58
-
Can you please write the detail coding of that? – Pradeep Anand Jan 10 '19 at 15:15