Firebase is one of NoSql database only available as a cloud service. It's a typical JSON tree tdatabase where you can perform in many other NoSQL database like MongoDB, Redis, or Casandra. However, there is a specific feature which differentiates Firebase against others.
Realtime Database
Let's imagine that you are developing a chatting app. When users add comments in a topic, the app will retrieve comments in order from a remote server which hosts a database. When the user is inactive in that chat room, the app still needs to retrieve other users comments constantly and periodically as long as the user stays in that chat room. I know how tricky to build this periodic synchronization from scratch. Firebase gives a solution. Once you point to a right datasource in firebase, it will retrieve all the data in it in realtime. This will save tremendous of your development time. The realtime database feature can be used as:
- chatting
- push notification
- news feed
- any kind of data storage which requires realtime sync
Can you imagine how easy to build push notification with Firebase without using GCM?
There are some other advantages using Firebase:
- cross-platform
- cloud-based messaging service
- authentication
Sample Codes
The sample codes are written in Android but web ir iOS usage is very similar as well.
Initialization
Add a dependency in your build.gradle file. That's all you need to use firebase.
compile 'com.google.firebase:firebase-database:9.6.1'
Then, you can initialize the firebase in your code and point it to a right database.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("messages");
Structure Database
Continued from the chatting app, you can structure the message database as below. Let's simplify that the message node contains all the message from the users. This will continuously grow as users add more comments.
"messages": {
{"message":"This is a test message"},{"message":"How are you?"}
}
Read**
The following method will be called once with the initial value and whenever data at this location is updated.
// Read from the database. Called whenever it's updated.
myRef.child("message").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = dataSnapshot.getValue(String.class);
Log.d(TAG, "Value is: " + value);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
Write
The write function is simple as below.
myRef.child("message").setValue("Hello, World!");
There are more features that firebase can leverage your app development. You can check more documentation from the reference.