Firebase Realtime Database In Android
Welcome to another post of Firebase series. We have already discussed about Firebase Remote Config, Firebase Authentication and Firebase Crash Report. Today we are going to discuss about Firebase Realtime Database.
As an android developer we always have a feeling that if we need to sync data between more number of users we need :
- Webservices/API
- MySQL database
- Some domain
- Server to host everything.
With Firebase Realtime Database we can avoid all above things. It is a database hosted on cloud. It is a NoSQL database. You will be allowed to store and sync data in JSON format. Each data will be stored as a JSON.
Whenever there is any change in database, other connected user will be notified with data change within a milliseconds.
Firebase Realtime Database can also work in offline, it will persist user data on disk. Once connectivity is reestablished, the client device receives any changes it missed, synchronizing it with the current server state.
Setup Firebase Realtime Database
Step 1 : Create a new project on Firebase Console. Enter you project name and select country, than click CREATE PROJECT
Step 2 : After creation of project click on Add Firebase to your Android app. Enter package name, App nickname(optional) and SHA-1 key(optional) and click on ADD APP.
Step 3 : You will receive google-services.json file, put it inside app/ folder of your project.
Step 4 : Add dependency to your root level build.gradle file.
1 2 3 4 |
dependencies { ... classpath 'com.google.gms:google-services:3.0.0' } |
Step 5 : Add dependency to your app/module level build.gradle file.
1 2 3 4 |
dependencies { ... compile 'com.google.firebase:firebase-database:10.2.4' } |
Step 6 : Add plugin at the bottom of your app-level build.gradle file.
1 |
apply plugin: 'com.google.gms.google-services' |
After adding google.json file and all setup you might get this error
Error:Execution failed for task ‘:app:processDebugGoogleServices’.
> Missing api_key/current_key object
It is a bug in google-services:3.0.0, but there is no need to worry about, once you add any service of the Firebase, replace the google.json file with newly created file. You can get new google.json file from Project Settings in Firebase console.
That’s it with the setup, not lets dig into coding part. But before going into it, take a look at Firebase rules also.
Default : It allows authenticated users to read and write data. They are useful if you want data open to all users of your app.
1 2 3 4 5 6 |
{ "rules": { ".read": "auth != null", ".write": "auth != null" } } |
Public : It allows everyone to access your application database i.e. anyone can read and write data.
1 2 3 4 5 6 |
{ "rules": { ".read": true, ".write": true } } |
User : It gives each authenticated user a personal node at /users/$user_id where $user_id is the ID of the user obtained through Authentication.
1 2 3 4 5 6 7 8 9 10 |
{ "rules": { "users": { "$uid": { ".read": "$uid === auth.uid", ".write": "$uid === auth.uid" } } } } |
Private : It will disable read and write operation for all users. Admin can only access data from Firebase Console.
1 2 3 4 5 6 |
{ "rules": { ".read": false, ".write": false } } |
In order to write data to Firebase Database, you need an instance.
1 |
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance(); |
Create a reference of your parent node and write data into it.
1 2 |
DatabaseReference databaseReference = firebaseDatabase.getReference("version"); databaseReference.setValue(BuildConfig.VERSION_NAME); |
It will create a node named “version” and writes value into it.
Read data added to database
1 2 3 4 5 6 7 8 9 10 11 |
databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Log.e("MainActivity", "version : " + dataSnapshot.getValue(String.class)); } @Override public void onCancelled(DatabaseError databaseError) { Log.e("MainActivity", "onCancelled: " + databaseError.toString()); } }); |
Here we have added string data so we can write dataSnapshot.getValue(String.class). If it is other datatype, you can mention it there.
Write an object to the database :
1 2 |
DatabaseReference databaseReference = firebaseDatabase.getReference("user"); databaseReference.setValue(new User("Android","Gig")); |
It will create a node named “user” and writes data into it.
Structured Data
As we know this is not the right way to write the data. We can have multiple users so data should be structured. Lets see how to make it.
1 2 |
databaseReference.push().setValue(new User("Android","Gig")); databaseReference.push().setValue(new User("Ravi","Rupareliya")); |
push() will create a unique id and User data will be stored inside that.
Listener for particular node
1 2 3 4 5 6 7 8 9 10 11 |
databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Log.e("MainActivity", "user : " + dataSnapshot.getValue(User.class).getFirstName()); } @Override public void onCancelled(DatabaseError databaseError) { } }); |
Whenever there is a change in specified node, onDataChange will be called on each active users device.
1 2 3 4 5 6 7 8 9 10 11 12 |
databaseReference.setValue(new User("Android","Gig")); databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { User user = dataSnapshot.getValue(User.class); Log.e("MainActivity", "user : " + user.getFirstName() + " " + user.getLastName()); } @Override public void onCancelled(DatabaseError databaseError) { } }); |
Still there are many things to learn about in Firebase Realtime Database. If it is possible i will come once again with some realtime applications. Until then enjoy coding 🙂
Ravi Rupareliya
Latest posts by Ravi Rupareliya (see all)
- Dialogflow Entities With Actions on Google - May 7, 2020
- Actions on Google Using Cloud Functions - February 3, 2020
- Create WhatsApp Stickers Android Application - April 19, 2019