Sunday, July 24, 2016

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.


8 comments:

  1. Digital Camera is the definitive guide to digital SLR photography and will show you how to improve any digital photo. It’s packed with practical photography advice and Photoshop tutorials to help you become ..sisteme camere supraveghere

    ReplyDelete
  2. That is the excellent one post here. Thank you and all the best.
    digital marketing company in india

    ReplyDelete
  3. Healrun is a health news blog we provide the latest news about health, Drugs and latest Diseases and conditions. We update our users with health tips and health products reviews. If you want to know any information about health or health product (Side Effects & Benefits) Feel Free To ask HealRun Support Team.

    ReplyDelete
  4. Supplements For Fitness administration. But Duromin has reports of heart pain, hallucinations, dry mouth, dizziness, seizures and even death. This makes it a very serious risk to health, especially for those who have a series of heart problems or other diseases, such as diabetes.I try very hard not to be predisposed when considering

    ReplyDelete
  5. Pilpedia is supplying 100 percent original and accurate information at each moment of time around our site and merchandise, and the intent is to improve the usage of good and pure health supplement. For More Info please visit Pilpedia online store.

    ReplyDelete
  6. Contact small businesses with relevant websites. Paid strategies that are easily scalable, like Facebook ads or a Google AdWords pay-per-click campaign can help to drive revenue while you spend the time required to reap the benefits of SEO. And remember, when adding external links a nice little trick to keep people on your site is to make the link open in a new tab or window. For example, with SEMRush , you can type your domain into the search box, wait for the report to run, and see the top organic keywords you are ranking for. Linking between your posts creates more ways for readers and Google to engage with your website.

    Make sure all your pages have the rel=canonical tag directing search engines to the main page. Search engines will recognize that you're referring to ‘smartphone' and give your site more SEO love. Longer posts typically rank better if the content is high quality and really relevant to a users search query. Internal links are somewhat similar to backlinks, with the exception that they do not technically improve your search rankings or domain authority on the same level. With all of the amazing and versatile website builders on the market, using Doodlekit to build a beautiful new site is about as good as using a Windows 98 computer to try and play the latest version of Call of Duty. https://www.reviewengin.com/7-best-wordpress-seo-tips-to-rank-google/


    ReplyDelete
  7. Making Content Shareable
    I naturally add hyperlinks in my content material and don’t need the Text Link Counter. I can use Search Console to verify what content material is listed in Google, and I by no means use the Yoast Admin Bar. In addition to themes and WordPress commonplace features, there are additionally a great deal of WordPress plugins to additional improve the search engine optimization capabilities of the platform. Yoast web optimization and All-in-One web optimization Pack are two plugins that we speak about very often, nevertheless, there are plenty more. Easy content creation — Content has turn out to be the software to face aside in search engines.

    Google Crawl Errors

    Even in case your title features a keyword, nobody will click on it if it doesn’t make sense. Make positive that your keywords not only precisely reflect the content material of your publish, but in addition sound natural inside it. Over time, your content will appeal to a loyal following and generate extra clicks and shares in the process. Both metrics will depend as a lot in search rankings as much as the web optimization tools you use, and will hold visitors returning to your blog. You can use each search engine optimization plugin obtainable on WordPress, however their influence can't outweigh poor content material.

    All you must do is analysis a synonym of your main keyword then incorporate both of these in your page title, web optimization title, and meta description. This is by FAR the most important part however you can also sprinkle your secondary keyword 1-2 times in your content material. You do NOT have to include both as full keywords (exact matches) otherwise your headline will look spammy. Redirect Manager – lets you repair crawl errors in Yoast’s Search Console tab by establishing redirects (but you can even use the Quick Page/Post Redirects). Yoast’s will mechanically setup redirects once a permalink is changed, which is nice, since most different redirect plugins don’t do this.

    You can even import existing redirects from the Redirection Plugin and .htaccess. I don’t want the Readability Analysis telling me if my sentences are too short/long.

    Although this isn’t as quick or simple as coming into a few keywords into a plugin, it’s arguably far more essential. Keep utilizing the tools, but in addition hold producing quality content material frequently to stretch their effectiveness. With SEO by Yoast, you'll be able to enter a target keyword for every weblog submit.

    It will immediately determine whether or not or not that keyword is present in your heading, web page title, URL, content, and meta description. Although you can establish all of those issues by yourself, it supplies a simple means to make sure that you’ve included your keyword in the entire right locations. Search engines rank pages on a number of components, together with URLs. If a URL doesn’t present a clear description of the web page’s content, it doesn’t get indexed as easily and, consequently, doesn’t rank very high. WordPress enables you to customise every URL, making each page of your weblog rank greater. https://www.reviewengin.com/5-simple-wordpress-seo-hacks-to-boost-your-google-ranking/

    ReplyDelete