Langsung ke konten utama

Introduction to Firebase Database for Android



I've already written a post about Firebase and its' features but features highlighted in the post are additional to the core functionality of Firebase.

What is this core functionality? Well, this is the thing that Firebase started from. It's Realtime Database.

A real-time database is, basically, the database that can effectively store dynamic data. By dynamic, I mean data that is constantly changing for example stocks prices.

Firebase Database

So Firebase has its' own built-in real-time database which you can use as a backend for your app. Let's consider the structure of this database.

First of all, it's worth to mention that this database is not relational and doesn't use tables as you might expect. It uses JavaScript Object Notation (JSON) to store the data so it's kinda "object-oriented" database. 

I think that this it an advantage at least for developers because JSON, in my opinion, is easier to understand than relational tables if you're working within an object-oriented language. Also, using JSON eliminates some pitfalls that are associated with relational tables but, as always, brings some others.

The second important thing that Firebase Database is stored in the cloud and Firebase provides its' own hosting for it so you don't need to care about it. The amount of space you allowed to work with is described in your subscription plan.

And the most important feature in terms of development is that you can set data change listeners that will fire every time data in the database is changed and moreover give you a snapshot of changed node in the object tree.

Now when we have a big picture let's dive in and look how it works.

Closer Look

From this point, I assume that you have an account for Firebase.

First of all, we need to create our application.

App creation window

You can choose any name you like whereas app URL should be unique for every app registered in firebase. 

When you successfully created your app you can enter your dashboard and see an empty database.


Now you can go ahead and add some data directly from the dashboard or use the SDK to do so from your Android, iOS or Web app. Let's try do add something manually.

Manually added nodes

The important thing to notice that every node in the tree has its' own URL, we will use it later to refer to the concrete piece of data and attach a change listener to it.

Android SDK

For instructions on how to add Firebase to your Android app visit this page.

To use the database in our app we should add this gradle dependency in our app 
com.google.firebase-database:9.2.1

Now let's write some data to our database using Android app. One of the greatest things about this SDK is that you can write into the database using Plain Old Java Objects (POJO). This feature gives you an opportunity to keep your code clean and on the consistent level of abstraction.

Let's create POJO for our messages

public class Message {
private String author;
private String message;

public Message (String auth, String msg) {
this.author = auth;
this.message = msg;
}

public String getAuthor() {
return author;
}

public String getMessage() {
return message;
}
}

Note that for every field in Message class there is a public getter. It's a rule of SDK. If you don't have a public getter for some of the field you may get an exception so be sure to check that.

And the actual write method will look like this.

private void addMessage(String author, String message) {
Firebase ref = new Firebase("https://tomasteryexmpl.firebaseio.com/chat/messages");
Firebase messageRef = ref.push();

messageRef.setValue(new Message());
}

It should be a method of the class that handles your database workflow. You can also pass composed Message object instead of author and message separately.

Let's do some clarifications. The ref variable stores a reference to the list of messages that we made earlier.

Method push() creates the unique key for the new entry in this list and returns its' reference in the database so messageRef stores reference to the new message.

When you have your reference you can easily write data to it using setValue(Object) method. And now you're done this method will successfully write your messages to the database and each message will have its' own unique key. Kinda easy, huh?

Let's look what happened to our data.

Added a message with unique code

Read the Database

In Firebase data reading differs from standard databases. To read from a database you should attach an asynchronous listener to the node you want to read. This listener will be triggered first time for initial state and every time data in this node is changed.

There are 2 types of listeners: ValueEventListener and ChildEventListener. The difference, basically, is that ValueEventListener will send you a snapshot of the whole object when it's changed while ChildEventListener will only send a snapshot of the changed child.

To listen for the messages it will be better to set a ChildEventListener to messages node so that we don't get the full list of messages every time a new message is sent.


private void setMessageListener() {
Firebase ref = new Firebase("https://tomasteryexmpl.firebaseio.com/chat/messages");

ref.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
Message newMsg = snapshot.getValue(Message.class);
addMessageToUI(newMsg);
}
//... ChildEventListener also defines onChildChanged, onChildRemoved,
// onChildMoved and onCanceled, covered in later sections.
});
}

And that's pretty all that you need to do to set a child listener to a node. Now every time a message is added to the database addMessageToUI will be called and you will see your message in your app. There are libraries that can do that for you (like Firebase UI) but these are out of the scope of the post.

To get more information about reading the database visit this page in Firebase Docs.

This is pretty all that you need to know to build a basic Android messaging app. For me, it looks extremely easy in comparison to all the backend mess that you would set up without Firebase.


Komentar

Postingan populer dari blog ini

FlatBuffers Android Tutorial

FlatBuffers is an efficient cross platform serialization library for C++, Java, C#, Go, Python and JavaScript. It was originally created at Google for game development and other performance-critical applications. FlatBuffers is Open Source (Apache license V2) and available on GitHub . It's currently used by:   Cocos2d-x , the open source mobile game engine and used to serialize the game data. Facebook uses it for client-server communication in the Android app (see the article) . Fun Propulsion Labs at Google in most of libraries and games. Solution overview  The schema will be defind in JSON format, then it will be converted to FlatBuffer format outside the application The Java classes of the Data model will be generated manually using flatc (FlatBuffer compiler) Step 1: Build FlatBuffers Download the source code in Google’s flatbuffers repository .  The build process is described on Google's documentation FlatBuffers Building .  On MacOS for example: Open the xcode proje

QR-Code Generator - Library

In this Post, I introduce my new Gradle Library. This Library is used to Generate QR Code Automatically for our specified input. How to Import the Library: Gradle: compile 'androidmads.library.qrgenearator:QRGenearator:1.0.0' Permission: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> How to use this Library: After importing this library, use the following lines to use this library. The following lines are used to generated the QR Code // Initializing the QR Encoder with your value to be encoded, type you required and Dimension QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension); try { // Getting QR-Code as Bitmap bitmap = qrgEncoder.encodeAsBitmap(); // Setting Bitmap to ImageView qrImage.setImageBitmap(bitmap); } catch (WriterException e) { Log.v(TAG, e.toString()); } Save QR Code as Image // Save with location, value, bitmap returned and type of Image(JPG/PNG). QRGSaver.save(s

Download file using Okio in Android

Okio is a library that complements java.io and java.nio to make it much easier to access, store, and process your data. Simply Okio is a modern I/O API for Java.  In this post, we will see how to download image or any file using Okio. Okio is component for OkHttp Coding Part Create a new project in Android Studio. Add following dependencies to your  app-level  build.gradle  file. compile 'com.squareup.okhttp3:okhttp:3.6.0' Don't forget to add the following permission in your AndroidManifest.xml <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> Implementation Paste the following code in your Activity and Here, I have kept as MainActivity.java public void downloadImg(View view) { try { Request request = new Request.Builder() .url(imageLink) .build(); new OkHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFail