'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) {

        }
    });


Solution 1:[1]

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.

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Alex Grebennikov