Firebase the dynamic database!

Pankaj Rai 🇮🇳
AndroidPub
Published in
7 min readMay 9, 2017

--

It’s a very popular database which is fast, dynamic and to few extent it’s free to use too. It offers lot’s of services like hosting, crashlytics, storage, dynamic database, cloud function, authentication, test lab for android, analytics and few more. It maintains NoSQL database where all the records are added in json format so let’s quickly see how to use firebase.

How to setup firebase?
First of all create an account at firebase.google.com then click on add project. You will see that a thumbnail gets created for you just click on that thumbnail then it will ask to select any of the 3 platform iOS, Android and web for which one you want to use firebase. Select Android and you will see screen like this

After selecting android this window will appear fill details and click on REGISTER APP

After clicking on REGISTER APP you will get a .json file containing all the required information about the project download that json file and place it to your app folder(ProjectName->app->paste it here). Now you have to add classpath at gradle

dependencies {
...
classpath 'com.google.gms:google-services:3.0.0'

// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}

also need to add dependencies along with apply plugin at app:gradle

apply plugin: 'com.google.gms.google-services'

Add this plugin to the bottom of your gradle file outside dependencies block.

The above mentioned steps are same for any of the firebase service that you want to use apart form these steps the extra thing that you have to do is just to add the dependency for the service that you want to use. Following are the list of services provided by firebase along with there dependencies

console.firebase.com

What is dynamic database?
You might have worked with mysql or oracle database these are non dynamic database this means that they will not alert the user automatically if the content in the table is changed. You have to explicitly call the method to get the records every time but dynamic database saves you from this burden whenever any data is altered or added in the database immediately you will get an alert. Best scenario is think of chat application which uses dynamic database to get the response as soon as any new data comes or old gets modified.

What firebase dynamic database offers?
Firebase is not restricted only till android you can create app using firebase for other platforms also.

cloud.google.com

You can setup firebase to Android,iOS and Web where the best part is all pointing to same database hence updation done by any device will reflect the changes to the remaining devices also irrespective of their platform.

What if my device is offline?
Well the best part is it even works as if you are online if you want to send some data to server but you are offline than it maintain the list of changes that you did and as soon as you come online it automatically sync the data to the server. Same way if database got updated and you were offline then as soon as you come online it will sync cached data with server. In order to use this feature you have to enable set persistence so that it will maintain an exact local copy in your device
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
you can add this in your application class.

Let’s add dynamic database
Add the following dependencies to your gradle file:
compile ‘com.google.firebase:firebase-database:10.2.4’

Data type supported by firebase
Firebase supports following data types:

  • String
  • Long
  • Double
  • Map<String,Object>
  • List<Object>

In your main activity get the reference for your database and use that reference to write data to your database. In order to write data to your database there are several ways:

use setValue() for writing single record:

mFirebaseDatabase.getReference(“child”) will create a child where the data can be written using setValue(). This will directly set the value to the child itself where the name of child will act as key.

Note: Trying to writing new data using setValue will overwrite the old one hence this will not add new data along with the old one.

Use setValue() for multiple records:

mDatabaseReference.child will create the sub-child and then by using setValue onto which will set the value to the sub-child. You can create multiple sub-child or even more nested childs.

Use push() if name of child doesn’t matter:

push() method generate some random string as a key and value can be set directly to it by using setValue(). This type of method is useful if the value is needed to be retrieved whereas key retrieval is not needed.

Use map to create well formed structure

By using map the key,value pair can be added to the child directly. Each of this key may have sub-child also as per the need. In order to do so you can just change the database reference to the appropriate child and then add content

The reference to the database is changed by using mFirebaseDatabase.getReference(“child/Age”); after changing this any value gets added or replaced to the child contains Age as key.

Firebase realtime database record structure
Firebase realtime database stores all record in a json like format so they form a tree like structure and good thing in that when you click on any key you will get the direct url to access it hence no need to parse full data based on your need just pass the url to start accessing the elements. In short all the keys have there own specific url that can be used to retrieve value.

How to retrieve data?

There are listeners to get the data as illustrated above so as per the need you can use any of these 3 listeners with the database reference to fetch the result. These listeners gets DataSnapshot from the server that contains the data at the specified location in the database at the time of the event. To get the value use dataSnapshot.getValue() and to count the number of children use dataSnapshot.getChildrenCount().
The simplest way to get the data is to create the model class where name of the variable is exactly the same name as given to the key in the database and there data type will the data type of the value for the corresponding key.

public class MainActivity extends AppCompatActivity {

FirebaseDatabase mFirebaseDatabase;
DatabaseReference mDatabaseReference;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference("child");

Map<String, String> map = new HashMap<>();
map.put("Name","Jas");
map.put("Age","25");
map.put("Country","USA");
mDatabaseReference.setValue(map);

mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
SampleModel sampleModel = dataSnapshot.getValue(SampleModel.class);
Log.e("Data snapshot","Fetched Name"+sampleModel.getName());
}

@Override
public void onCancelled(DatabaseError databaseError) {
Log.e("Data snapshot error",""+databaseError);
}
});
}
}

Model constructed is same exactly with the same name as key and data type as the type of value.

public class SampleModel {

private String Country;
private String Age;
private String Name;


public String getCountry() {
return Country;
}

public void setCountry(String country) {
Country = country;
}

public String getAge() {
return Age;
}

public void setAge(String age) {
Age = age;
}

public String getName() {
return Name;
}

public void setName(String name) {
Name = name;
}
}

If you are using addChildEventListener than that will not give all the record at once unlike addValueEventListener that will give the portion of data as the snapshot.

Not to forget that firebase cloud messaging has replaced the Google cloud messaging service as both are their own product so you can say that they merged their service to a single platform now but in turn FCM uses GCM internally but soon the support for GCM will be stopped so it’s better to migrate to FCM to get the latest features. Support to GCM will stop doesn’t mean that app that are using GCM for notification will no longer works rather it only means that they will be missed out with the new features that will be added to FCM.

--

--

Pankaj Rai 🇮🇳
AndroidPub

Software Engineer | GDE Android & Firebase | YouTuber — All Techies