Pritam Pawade
Pritam Pawade

Reputation: 717

Get realtime data change update when data changes on Firebase Realtime Database

I have written this code to fetch the data. But I want to fetch updates without restarting the activity as data changes in real-time in the database.

I want to show data dynamically:

FirebaseDB.batch.child(batch).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            //Update recyclerview here
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

Upvotes: 1

Views: 3469

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138824

If you need to get data in real-time, you should use a real-time listener. To solve this, please change your code to:

FirebaseDB.batch.child(batch).addValueValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            //Update recyclerview here
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
            Log.d("TAG", error.getMessage()); //Never ignore potential errors!
        }
    });

See, I have used Query's addValueEventListener():

Add a listener for changes in the data at this location.

instead of addListenerForSingleValueEvent() which:

Add a listener for a single change in the data at this location.

Upvotes: 2

Alex Grebennikov
Alex Grebennikov

Reputation: 170

You are using wrong listener. According to firebase documentation this listener will be triggered only once.

You need to use simple ValueEventListener as stated in docs

Upvotes: 1

Related Questions