Home > Enterprise >  Reading some of data (not all) from a Firebase database node
Reading some of data (not all) from a Firebase database node

Time:09-14

I'm working on project in which I need to read the firebase node in this manner:

Suppose I have a node messages in a firebase realtime database. In that node, I have 20, 000 messages. When a user enter in the message box, I need to show messages. But Its too time consuming to read all 20, 000 messages at a time.

What I want it, to read 30-40 messages at a time and show those to the user. When user press more message button, I will read another 30-40 messages and show them to users. and so on.... it would faster and convenient.

But I can't find any way to make the things work like this. I tried with ValueEventListener(), but it reads all the data in that messages node and it's time consuming. I also tried reference.limitToFirst(30) but it read first 30 messages, then what do I do? How can I read next 30 messages?

Could I have present my problem clearly? :( Thanks in advance.

CodePudding user response:

But it's too time-consuming to read all 20,000 messages at a time.

20,000 messages can be considered a lot of data. So I strongly recommend against loading such an amount of data in one go.

What I want is, to read 30-40 messages at a time and show those to the user. When the user presses more message button, I will read another 30-40 messages and show them to users. and so on.... it would faster and more convenient.

What you're looking for is called pagination. This means that you need to load the data progressively in smaller chunks. You need to load a group of 30-40 messages, one after another. This was already covered a lot of times before, and this question already has a lot of solutions for the Realtime Database:

I also tried reference.limitToFirst(30) but it read the first 30 messages, then what do I do? How can I read the next 30 messages?

I recommend you have a look at some of those questions and give it a try. If you have a hard time implementing it, then show us an MCVE with what you have tried, and this way, I and other Firebase developers can help you.

However, if you consider at some point in time trying using Cloud Firestore, I think that this answer will help:

If you want to go further and try using Jetpack Compose, then I think that this resource will help:

How to implement pagination in Firestore using Jetpack Compose?

  • Related