Skip to content Skip to sidebar Skip to footer

How To Get Only Newly Added Data From The Firebase?

As i am creating the chat app, for it i am using the Firebase. It works perfectly, only one problem which i am getting that each time i am getting whole list of data from Firebase,

Solution 1:

You can use addChildEventListener() to you DatabaseReference which will notify you on different callback method when any child is add/removed/updated/deleted or moved

databaseRef.addChildEventListener(new ChildEventListener() {

        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
            // If any child is added to the database reference
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            // If any child is updated/changed to the database reference
        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
          // If any child is removed to the database reference
        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
             // If any child is moved to the database reference
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            Log.e("FirebaseListAdapter", "Listen was cancelled, no more updates will occur");
        }
    });

The DataSnapshot in each callback will provide you the information of the child

Solution 2:

I think you can use this listener onChildAdded() I provided a link to the documentation.

Listen for child events

Solution 3:

You can try Query for query on database,add on child as date and time and query based on that data filed after every result update the query to last sync date and time

Solution 4:

This is by design, in a real-time system there is no concept of the "latest" data because it's always changing. However, if you want to only display items added to the list after the page has loaded, you can do the following:

var newItems = false;
var eventsList = newFirebase('https://*****-messages.firebaseio.com/');

eventsList.on('child_added', function(message) {
  if (!newItems) return;
  var message = message.val();
  $.notification(message.message);
});
eventsList.once('value', function(messages) {
  newItems = true;
});

above answer original by (anant)

(my) another solution

if you have control over your database schema you can add a 'datetime' element in your object and store the value of the time just before adding it to database in Epoch format, then you can simply get the list of objects in newly added order with limit like this.

ds.orderBy("datetimeSent", Direction.DESCENDING).limit(10);

Post a Comment for "How To Get Only Newly Added Data From The Firebase?"