Designing and understanding how to retrieve realtime data from the Firebase Database

suggest change

This example assumes that you have already set up a Firebase Realtime Database. If you are new to Firebase, see the setup guide for how to add Firebase to your Android project.

First, add the dependency of the Firebase Database to the app level build.gradle file:

compile 'com.google.firebase:firebase-database:9.4.0'

Now, let us create a chat app which stores data into the Firebase Database.

Step 1: Create a class named Chat

Just create a class with some basic variables required for the chat:

public class Chat{
    public String name, message;
}

Step 2: Create some JSON data

For sending and retrieving data, Firebase stores JSON. Assume the chats already exist under a chats node. The data could look as follows:

{
    "chats": {
        "id1": {
            "name": "John Doe",
            "message": "My first Message"
        },
        "id2": {
            "name": "John Doe",
            "message": "Second Message"
        },
        "id3": {
            "name": "John Doe",
            "message": "Third Message"
        }
    }
}

Step 3: Adding the listeners

There are several listener types. The following example uses a ChildEventListener:

DatabaseReference chatDb = FirebaseDatabase.getInstance().getReference() // Referencing the root of the database.
        .child("chats"); // Referencing the "chats" node under the root.

chatDb.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        // This function is called for every child. With the data above, it is called three times.
        
        // Retrieving the Chat object from this function is simple.
        Chat chat; // Declare the chat object.

        // Use the getValue function in the dataSnapshot and pass the object's class name to
        // which you want to convert and get data. In this case it is Chat.class.
        chat = dataSnapshot.getValue(Chat.class);

        // Now you can use this chat object and add it into an ArrayList or something like
        // that and show it in the recycler view.
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String s) {
        // This function is called when a child value changes. dataSnapshot will
        // get the data with the key of the child, so you can swap the new value with the
        // old one in the ArrayList or something like that.

        // To get the key, use the .getKey() function.
        // To get the value, use code similar to the above one.
    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {
        // This function is called when a child node is removed. dataSnapshot
        // contains the removed child's data.

        // To get the key, use dataSnapshot.getKey().
    }

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String s) {
        // This function is called when a child node moves to a different position.
        // dataSnapshot is the moved child. s is the key of the previous sibling.

        // To get the moved child's key, use dataSnapshot.getKey().
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // If anything goes wrong, this function is going to be called.

        // You can get the exception by using databaseError.toException();
    }
});

Step 4: Add data to the database

Just create a Chat class object and add the values as follows:

Chat chat=new Chat();
chat.name="John Doe";
chat.message="First message from android";

Now get a reference to the chats node as done in the retrieving session:

DatabaseReference chatDb = FirebaseDatabase.getInstance().getReference().child("chats");

Each chat is its own child under chats. push() returns a DatabaseReference for a new unique child, and that is where the chat is written.

Example

// The parameter is the chat object that was newly created a few lines above.
chatDb.push().setValue(chat);

setValue() notifies listeners on the chats node, including listeners on the same device. With the ChildEventListener above, a new child calls onChildAdded.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents