2

Hello Everyone, I have loaded some data from Firebase Realtime Database in the App using Query.

This is the Simple code :

  Query query = databaseReference.orderByChild("name").startAt(data).endAt(data + "\uf8ff");

  options = new FirebaseRecyclerOptions.Builder<HomeModel>().setQuery(query, HomeModel.class).build();

My database structure is simple ;

M38dJdquf4jE(the random key)
name : "John Doe"
Image : "image link"

Because of orderByChild("name"), whenever a new Data is inserted in the Database is not according to the Time the data is inserted. Instead, it inserts the data in the recyclerView in a Random Order.

How can I fix it, so that the Last data inserted is always at the last in the recyclerView and not inserted in a random manner.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Sainita
  • 332
  • 1
  • 4
  • 16

1 Answers1

2

Because of orderByChild("name"), whenever a new Data is inserted in the Database is not according to the Time

When you are using:

.orderByChild("name")

It means that the results that are coming from the database will be ordered according to the values that exist in the "name" property, and not according to a "time".

Instead, it inserts the data in the RecyclerView in a Random Order.

As said above, that's definitely not a random order. If you need to get the results according to the "time" of the addition, then you have two options.

If, for example, the "M38dJdquf4jE" is a pushed key that is provided by the "push()" method, you can use Query's orderBykey() method, which:

Creates a query in which child nodes are ordered by their keys.

You'll get the results ordered because the pushed keys contain a time component.

If those keys are not provided by the "push()" method, to have an order according to a time component, then you should add a property of type "timestamp", as explained in my answer from the following post:

Once you have that new property in place, you can use:

.orderByChild("timestamp")

To have the results ordered ascending. If you need however a descending order, then you can use my answer from the following post:

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193