Now you are ready to work with the Realtime Database in Android.
For example you write a Hello World message to the database under the message key.
Firebase Realtime DataBase event handler
First Initialize FirebaseDatabase:
Write to your database:
Read from your database:
Retrieve Data on Android events:
Denormalization: Flat Database Structure
Denormalization and a flat database structure is neccessary to efficiently download separate calls. With the following structure, it is also possible to maintain two-way relationships. The disadvantage of this approach is, that you always need to update the data in multiple places.
For an example, imagine an app which allows the user to store messages to himself (memos).
Desired flat database structure:
The used memo class
Retrieving the memos of a user
Creating a memo
After the push, or database looks like this:
Designing and understanding how to retrieve realtime data from the Firebase Database
This example assumes that you have already set up a Firebase Realtime Database. If you are a starter, then please inform yourself here on how to add Firebase to your Android project.
First, add the dependency of the Firebase Database to the app level build.gradle file:
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:
Step 2: Create some JSON data
For sending/retrieving data to/from the Firebase Database, you need to use JSON. Let us assume that some chats are already stored at the root level in the database. The data of these chats could look like as follows:
Step 3: Adding the listeners
There are three types of listeners. In the following example we are going to use the childEventListener:
Step 4: Add data to the database
Just create a Chat class object and add the values as follows:
Now get a reference to the chats node as done in the retrieving session:
Before you start adding data, keep in mind that you need one more deep reference since a chat node has several more nodes and adding a new chat means adding a new node containing the chat details. We can generate a new and unique name of the node using the push() function on the DatabaseReference object, which will return another DatabaseReference, which in turn points to a newly formed node to insert the chat data.
The setValue() function will make sure that all of the application's onDataChanged functions are getting called (including the same device), which happens to be the attached listener of the "chats" node.
Listening for child updates
Take a use case, like a chat app or a collaborative grocery list app (that basically requires a list of objects to be synced across users). If you use firebase database and add a value event listener to the chat parent node or grocery list parent node, you will end with entire chat structure from the beginning of time (i meant beginning of your chat) every time a chat node is added (i.e. anyone says hi). That we don't want to do, what we are interested in is only the new node or only the old node that got deleted or modified, the unchanged ones should not be returned.
In this case we can use ChildEvenListener. Without any further adieu, here is code sample (see prev sections for sample JSON data):
Method names are self explanatory. As you can see whenever a new user is added or some property of existing user is modified or user is deleted or removed appropriate callback method of child event listener is called with relevant data. So if you are keeping UI refreshed for say chat app, get the JSON from onChildAdded() parse into POJO and fit it in your UI. Just remember to remove your listener when user leaves the screen.
onChildChanged() gives the entire child value with changed properties (new ones).
onChiledRemoved() returns the removed child node.
Retrieving data from firebase
I am gonna assume you already know about adding gradle dependencies firebase in android studio. If you don't just follow the guide from here. Add your app in firebase console, gradle sync android studio after adding dependencies. All dependencies are not needed just firebase database and firebase auth.
Now that we know how data is stored and how to add gradle dependencies let's see how to use the imported firebase android SDK to retrieve data.
create a firebase database reference
from here you can chain multiple child() method calls to point to the data you are interested in. For example if data is stored as depicted in previous section and you want to point to Bruce Wayne user you can use:
Or simply pass the whole reference to the JSON object:
Now that we have the reference of the data we want to fetch, we can use listeners to fetch data in android apps. Unlike the traditional calls where you fire REST API calls using retrofit or volley, here a simple callback listener is required to get the data. Firebase sdk calls the callback methods and you are done.
There are basically two types of listeners you can attach, one is ValueEventListener and the other one is ChildEventListener (described in next section). For any change in data under the node we have references and added listeners to, value event listeners return the entire JSON structure and child event listener returns specific child where the change has happened. Both of these are useful in their own way. To fetch the data from firebase we can add one or more listeners to a firebase database reference (list userDBRef we created earlier).
Here is some sample code (code explanation after code):
Did you notice the Class type passed. DataSnapshot can convert JSON data into our defined POJOs, simple pass the right class type.
If your use case does not require the entire data (in our case user_base table) every time some little change occurs or say you want to fetch the data only once, you can use addListenerForSingleValueEvent() method of Database reference. This fires the callback only once.
Above samples will give you the value of the JSON node. To get the key simply call:
Retrieving data with pagination
When you have a huge JSON database, adding a value event listener doesn't make sense. It will return the huge JSON and parsing it would be time consuming. In such cases we can use pagination and fetch part of data and display or process it. Kind of like lazy loading or like fetching old chats when user clicks on show older chat. In this case Query can used.
Let's take the our old example in previous sections. The user base contains 3 users, if it grows to say 3 hundred thousand user and you want to fetch the user list in batches of 50:
Here value or child events can be added and listened to. Call query again to fetch next 50. Make sure to add the orderByChild() method, this will not work without that. Firebase needs to know the order by which you are paginating.
Understanding firebase JSON database
Before we get our hands dirty with code, I feel it is necessary to understand how data is stored in firebase. Unlike relational databases, firebase stores data in JSON format. Think of each row in a relational database as a JSON object (which is basically unordered key-value pair). So the column name becomes key and the value stored in that column for one particular row is the value. This way the entire row is represented as a JSON object and a list of these represent an entire database table. The immediate benefit that I see for this is schema modification becomes much more cheaper operation compared to old RDBMS. It is easier to add a couple of more attributes to a JSON than altering a table structure.
here is a sample JSON to show how data is stored in firebase:
This clearly shows how data that we used to store in relational databases can be stored in JSON format. Next let's see how to read this data in android devices.
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0