Firebase Realtime database is a cloud hosted database that supports multiple platforms Android, iOS and Web. All the data is stored in JSON format and any changes in data, reflects immediately by performing a sync across all the platforms & devices. This allows us to build more flexible realtime apps easily with minimal effort.

This article covers basics integration of firebase realtime database. The other concepts like performs CRUD operations, data validations, firebase access rules also covered. If you are new to firebase, I suggest you check my other articles about Firebase Auth and Firebase Analytics to improve your knowledge over firebase.

firebase-realtime-database-android

1. How the Data is Stored – JSON Structured

Firebase realtime database is a schemaless database in which the data is stored in JSON format. Basically the entire database is a big JSON tree with multiple nodes. So when you plan your database, you need to prepare the json structure in way that the data is accessible in easier way by avoiding nesting of child nodes.

Here is an example of storing list of user profiles and posts in json tree. You can go through firebase Structure Your Database guide to learn the best practises while defining the database structure.

{
  "users": [
    {
      "name": "Ravi Tamada",
      "email": "ravi@androidhive.info",
      "address": "XXX, XXXX, 1234"
    }
  ],
  "posts": [
    {
      "id": 100,
      "author": "Ravi Tamada",
      "content": "This is awesome firebase realtime database...",
      "timestamp": "13892733894"
    }
  ]
}

2. Offline Data

Firebase provides great support when comes to offline data. It automatically stores the data offline when there is no internet connection. When the device connects to internet, all the data will be pushed to realtime database. However enabling disk persistence stores the data offline even though app restarts. Disk persistence can be enabled by calling below one line code. Here is complete guide about firebase offline capabilities.

FirebaseDatabase.getInstance().setPersistenceEnabled(true);

3. Performing CRUD Operations

Before getting into the android app, I would like to give you basic information about performing CRUD operations on to realtime database. Later we’ll combine all these concepts together to build a simple app with firebase realtime database as backend.

In order to perform any operation on to database whether it can be read or write, you need to get the reference to database first. The below code gives you reference to database JSON top node. From here you need to use the child node names to traverse further.

private DatabaseReference mDatabase;

mDatabase = FirebaseDatabase.getInstance().getReference();

3.1 Inserting Data

To insert data, you can use setValue() method on to database reference path. This will create or update the value on path provided. For an example below code inserts a node called “copyright” in json top level.

DatabaseReference mRef = mDatabase.getReference("copyright");

mRef.setValue("ยฉ2016 androidhive. All rights Reserved");

The realtime database accepts multiple data types String, Long, Double, Boolean, Map<String, Object>, List<Object> to store the data. You can also use custom java objects to store the data which is very helpful when storing model class directly in database.

Let’s say you want to store user profile in the database. First you need to create User model with an empty constructor and other properties.

@IgnoreExtraProperties
public class User {

    public String name;
    public String email;

    // Default constructor required for calls to
    // DataSnapshot.getValue(User.class)
    public User() {
    }

    public User(String name, String email) {
        this.name = name;
        this.email = email;
    }
}

As every user needs a unique Id, you can generate one by calling push() method which creates an empty node with unique key. Then get the reference to ‘users’ node using child() method. Finally use setValue() method to store the user data.

DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("users");

// Creating new user node, which returns the unique key value
// new user node would be /users/$userid/
String userId = mDatabase.push().getKey();

// creating user object
User user = new User("Ravi Tamada", "ravi@androidhive.info");

// pushing user to 'users' node using the userId
mDatabase.child(userId).setValue(user);

By running the above code, a new user node will be inserted in database with a unique key value. In general, the user id should be acquired by implementing Firebase Auth in your app which gives you authId that acts as user id.

{
  "users": [
    "-KTYWvZG4Qn9ZYTc47O6" : {
      "email" : "ravi@androidhive.info",
      "name" : "Ravi Tamada"
    },
    {
      ...
    }
  ]
}

3.2 Reading Data

To read the data, you need to attach the ValueEventListener() to the database reference. This event will be triggered whenever there is a change in data in realtime. In onDataChange() you can perform the desired operations onto new data.

Below is the event listener that is triggered whenever there is a change in user profile data that we created earlier.

mDatabase.child(userId).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        User user = dataSnapshot.getValue(User.class);

        Log.d(TAG, "User name: " + user.getName() + ", email " + user.getEmail());
    }

    @Override
    public void onCancelled(DatabaseError error) {
        // Failed to read value
        Log.w(TAG, "Failed to read value.", error.toException());
    }
});

3.3 Updating Data

To update data, you can use the same setValue() method by passing new value. You can also use updateChildren() by passing the path to update data without disturbing other child nodes data.

For example if you want to update only the user email, you can use below code block.

String newEmail = 'androidhive@gmail.com';

mDatabase.child(userId).child("email").setValue(newEmail);

3.4 Deleting Data

To delete data, you can simply call removeValue() method on to database reference. You can also pass null to setValue() method which do the same delete operation.

You can learn more about performing CRUD operations onto more advanced data like Lists of data here.

4. Security & Rules

Firebase rules provides a way to identify user role while performing read and write operations. These rules will acts a security layer on the server before perform any CRUD operation. By default the rules allows user to perform read & write operation only after authentication.

The below rules allow authenticated users only to read or write data.

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

Below rules allows everyone to read & write data without authentication.

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

You can also use these rules to validate data before inserting into database. For example below rules validates the name to be less than 50 chars and email to be valid using email regular expression.

{
	"rules": {
		".read": true,
		".write": true,
		"users": {
			"$user": {
				"name": {
					".validate": "newData.isString() && newData.val().length < 50"
				},
				"email": {
					".validate": "newData.isString() && newData.val().matches(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$/i)"
				}
			}
		}
	}
}

Go through firebase security & rules guide to learn more about the security concepts.

Now we have enough knowledge to get started with an android project. Let’s create one and see how to integrate the realtime database with an example app.

5. Creating Android Project

1. First thing you need to do is go to https://firebase.google.com/ and make an account to gain access to their console. After you gain access to the console you can start by creating your first project.

2. Give the package name of your project (mine is info.androidhive.firebase) in which you are going to integrate the Firebase. Here the google-services.json file will be downloaded when you press add app button.

android-creating-firebase-app

3. Create a new project in Android Studio from File โ‡’ New Project. While filling the project details, use the same package name which you gave in firebase console. In my case I am using same info.androidhive.firebase.

4. Paste the google-services.json file to your project’s app folder. This step is very important as your project won’t build without this file.

5. Now open the build.gradle located in project’s home directory and add google playstore dependency.

dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0'
        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
    }

6. Open app/build.gradle and add firebase database dependency. At the very bottom of the file, add apply plugin: ‘com.google.gms.google-services’

dependencies {
    // Adding support library for this demo app
    compile 'com.android.support:design:24.2.1'

    compile 'com.google.firebase:firebase-database:9.6.1'
}

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

7. In order to store user profile, we need a model class called User.java. Create a class named User.java and add below class properties. If You want you can add few more properties like address, mobile etc.,

package info.androidhive.firebase;

import com.google.firebase.database.IgnoreExtraProperties;

/**
 * Created by Ravi Tamada on 07/10/16.
 * www.androidhive.info
 */

@IgnoreExtraProperties
public class User {

    public String name;
    public String email;

    // Default constructor required for calls to
    // DataSnapshot.getValue(User.class)
    public User() {
    }

    public User(String name, String email) {
        this.name = name;
        this.email = email;
    }
}

8. Open the layout file of main activity activity_main.xml and add the below layout. This layout creates a simple form where you can enter the profile data to store in database.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="info.androidhive.firebase.MainActivity">

    <TextView
        android:id="@+id/txt_user"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_horizontal_margin"
        android:textSize="20dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/name"
                android:inputType="textCapWords"
                android:maxLines="1" />

        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/email"
                android:inputType="textEmailAddress"
                android:maxLines="1" />

        </android.support.design.widget.TextInputLayout>

        <Button
            android:id="@+id/btn_save"
            style="?android:textAppearanceSmall"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:background="@color/colorPrimary"
            android:text="@string/action_save"
            android:textColor="@android:color/white"
            android:textStyle="bold" />

    </LinearLayout>

</LinearLayout>

9. Open MainActivity.java and do the below necessary changes. The code is very simple and easily understandable.

Our goal is to create the json structure as below in which ‘app_title’ stores the app title. ‘users’ stores user profiles as an array of nodes.

{
  "app_title" : "Realtime Database",
  "users" : {
    "-KTYWvZG4Qn9ZYTc47O6" : {
      "email" : "ravi@androidhive.info",
      "name" : "Ravi Tamada"
    }
  }
}

> getReference(“app_title”) create a node named app_title which stores the toolbar title.

> getReference(“users”) gets reference to users node.

> createUser() method stores a new user in realtime database

> updateUser() method updates user information like name and email.

package info.androidhive.firebase;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private TextView txtDetails;
    private EditText inputName, inputEmail;
    private Button btnSave;
    private DatabaseReference mFirebaseDatabase;
    private FirebaseDatabase mFirebaseInstance;

    private String userId;

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

        // Displaying toolbar icon
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setIcon(R.mipmap.ic_launcher);

        txtDetails = (TextView) findViewById(R.id.txt_user);
        inputName = (EditText) findViewById(R.id.name);
        inputEmail = (EditText) findViewById(R.id.email);
        btnSave = (Button) findViewById(R.id.btn_save);

        mFirebaseInstance = FirebaseDatabase.getInstance();

        // get reference to 'users' node
        mFirebaseDatabase = mFirebaseInstance.getReference("users");

        // store app title to 'app_title' node
        mFirebaseInstance.getReference("app_title").setValue("Realtime Database");

        // app_title change listener
        mFirebaseInstance.getReference("app_title").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Log.e(TAG, "App title updated");

                String appTitle = dataSnapshot.getValue(String.class);

                // update toolbar title
                getSupportActionBar().setTitle(appTitle);
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.e(TAG, "Failed to read app title value.", error.toException());
            }
        });

        // Save / update the user
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = inputName.getText().toString();
                String email = inputEmail.getText().toString();

                // Check for already existed userId
                if (TextUtils.isEmpty(userId)) {
                    createUser(name, email);
                } else {
                    updateUser(name, email);
                }
            }
        });

        toggleButton();
    }

    // Changing button text
    private void toggleButton() {
        if (TextUtils.isEmpty(userId)) {
            btnSave.setText("Save");
        } else {
            btnSave.setText("Update");
        }
    }

    /**
     * Creating new user node under 'users'
     */
    private void createUser(String name, String email) {
        // TODO
        // In real apps this userId should be fetched
        // by implementing firebase auth
        if (TextUtils.isEmpty(userId)) {
            userId = mFirebaseDatabase.push().getKey();
        }

        User user = new User(name, email);

        mFirebaseDatabase.child(userId).setValue(user);

        addUserChangeListener();
    }

    /**
     * User data change listener
     */
    private void addUserChangeListener() {
        // User data change listener
        mFirebaseDatabase.child(userId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                User user = dataSnapshot.getValue(User.class);

                // Check for null
                if (user == null) {
                    Log.e(TAG, "User data is null!");
                    return;
                }

                Log.e(TAG, "User data is changed!" + user.name + ", " + user.email);

                // Display newly updated name and email
                txtDetails.setText(user.name + ", " + user.email);

                // clear edit text
                inputEmail.setText("");
                inputName.setText("");

                toggleButton();
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.e(TAG, "Failed to read user", error.toException());
            }
        });
    }

    private void updateUser(String name, String email) {
        // updating the user via child nodes
        if (!TextUtils.isEmpty(name))
            mFirebaseDatabase.child(userId).child("name").setValue(name);

        if (!TextUtils.isEmpty(email))
            mFirebaseDatabase.child(userId).child("email").setValue(email);
    }
}

Run & test the app once. You should be able to see the changes in realtime in your firebase console. Check the Demo video that shows how to run and test the app.

android-firebase-realtime-database

6. Pricing

Unlike Analytics, Cloud Messaging, Crash Reporting and other services, firebase realtime database is not completely free. There are certain limitations in Free plan. You need to pay few bucks for the usage of number of connections, disk usage and network usage. For more information check out the firebase pricing plans.

Here is the quick overview of realtime database pricing details (as of Oct 12th, 2016)

Realtime Database Pricing

  Free $25 per month Pay as you go
Simultaneous connections 100 Unlimited Unlimited
GB stored 1 GB 2.5 GB $5/GB
GB downloaded 10 GB 20 GB $1/GB
Daily private backups No Yes Yes

7. References

Security rules:
https://firebase.google.com/docs/database/security/quickstart#sample-rules

Firebase Blog
https://firebase.googleblog.com/2016/07/have-you-met-realtime-database.html

Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • Dammy

    I really wished data presentation on Firebase dashboard are in table format (like Parse.com). JSON presentation isn’t OK especially for much data sets.

    Am I the only thinking this way?

    • Yeah, but hopefully google might comes with a new UI.

  • Mezoooo

    Hello Mr. Ravi Thank you so much for your hard effort and for great tutorial. I am looking in a relation between users and how to make for specific user to look for some other information and others no. and adding friends and remove friends somethings like this. Thank you

  • Thato Rammoko

    Hi Ravi Thank you for the Tuts they are are amazing. I have one question though, how do I create relationships between JSON Objects. In SQL we archive that via foreign keys, so whats the JSON format solution?

    • Firebase is suggesting to duplicate the data in order to have the relationship. Check their docs where then gave examples of Chat App.

  • Mohit Khaitan

    Thanks a ton Ravi. You nearly solved my probelm. You write great tutorials. I refer your tutorials to my juniors as well and it helps them too.

    • Thanks Mohit for suggesting the blog to others ๐Ÿ™‚

  • Nizzam

    Hi Ravi, is that possible to store image / video instead of text using firebase ?

    • Mouad Ghandi

      Yes It is possible

  • PINKesh Darji

    Hello Ravi,
    Can you please provide some samples to implement 1:1 chat with data structure in firebase?
    I have came across others samples but they all are for group chat.But I need develop complete one to one chat using firebase.

  • Vinayaka SP

    Hi, i got redirected by you from Login tutorial !
    well its working as a charm. but i have a small issue.
    let me explain in detail.
    I have combined auth and database into single project.
    When a user register from my app, user name, mail id and password get stored in database. i successfully pushed data to database. But when a registered user deletes his account and when he creates account with same email id, the old data is not getting updated instead it creates another node.
    for ex: i registered with email id as sp.vinayaka@google.com. then i removed the account from app and re registered again with same mail id. but node created was new one.
    Here is how my database looks like.
    https://uploads.disquscdn.com/images/887a764ec84854dce0cda15d4cc7c0fed8eb5753f6f1d9476dd7d54c536a7f91.png
    i want to add primary key concept to email id. i dont know how to do this exactly ๐Ÿ™

    hope you’ll help me.

    • Hi SP

      When you combine auth with realtime db, you need to use authId as primary key. Replace the below code

      String userId = mDatabase.push().getKey();

      use authId instead of mDatabase.push().getKey(). So that the authId will be same all the time for an user.

      • Vinayaka SP

        Thank you, will try it out.

        • Kenneth Stephen

          Bro , Were you able to achieve what you wanted? .. I have the same problem ๐Ÿ™

          • Vinayaka SP

            Nope not yet i’m still searching. Please let me know if you get any solution.

      • Vinayaka SP

        I have to directly use authId instead of mDatabase.push().getKey() ?
        or authId = mDatabase.push().getKey() ?

  • varun dusane

    hi sir, i want know that how to fetch list files stored in firebase storage because i have uploaded some files in firebase storage and want to show them in android app.. plz help.. ThanK you

  • Shubham Tyagi

    Hi ravi…really helpfull tutorials and blog…need some help….i am creating a app that has 2 login page…Operator and Customer….i have created the auth object and i can login perfectly…but…when i login into customer’s account it automatically logged me in into operators account…what i want here is that no customer can login into operator account with their email id and pass….same goes with the operator….if operator tries to login it fetches data from operators side…and when customer tries to login….if excludes the operator’s details while fetching the data…

  • Ahmed Dusmatov
  • Kassen Dauren

    Ravi hello, I guess you are really experienced mobile developer, so I wanna know, how can I retrieve data from Firebase and show it on ListView, can you make simple tutorial or give some advice?

  • Hi Ravi ,
    I really appreciate your effort .Thanks For sharing this post

    • You are welcome ๐Ÿ™‚

      • shashi patil

        hi ravi.. i am getting error as call to undefined method mysqli_stmt::get_result while using in hostinger… what will be the issue because i have used ur php scripts for login and registration in it.. the same scripts are working fine in xampp but in hostinger it is giving error.

  • Robby

    Great tutor brother. Thanks

  • Avik Sarkar

    Thank you for taking so much trouble to document these steps for us… ๐Ÿ™‚

  • Marcos Melgosa Vรกzquez

    Hi ravi, my comment is just to say… Congratulations! All your tutorials helped me a lot solving many problems and needs of some of my apps, I started wth some tutorials from the webPage Hermosa Programacion, and it was very helpful in that moment, but your tutorials deal with deeper topics, and now that I work on this to live, your tutorials help a lot… you’re great, keep up like this, and again congrats for your tutorials ๐Ÿ™‚

    • You are most welcome Marcos. All the best with your development.

  • Neha Sharma

    Hi Ravi… All Your Tutorials Are Very Helpful. I wanna request you to make a tutorial based on caching.
    For Example If we want to make an app like JUSTDIAL and we want to load all listview data from cache .
    So How Can We do that?
    Thanx In Advance….keep smiling…

  • Hitesh Danidhariya

    Hi Ravibhai,
    Can I use Firebase Realtime database to store Images?

    • Belmira Nahary Matos

      you can use the firebase storage to store Images

  • Lokendra Narware

    11-11 05:42:26.871 11888-11888/? I/art: Late-enabling -Xcheck:jni
    11-11 05:42:26.911 11888-11888/ln.uiimagefirebase I/InstantRun: Instant Run Runtime started. Android package is ln.uiimagefirebase, real application class is null.
    11-11 05:42:26.959 11888-11888/ln.uiimagefirebase W/linker: /system/lib64/libfilterUtils.so: unused DT entry: type 0x6ffffffe arg 0x808
    11-11 05:42:26.959 11888-11888/ln.uiimagefirebase W/linker: /system/lib64/libfilterUtils.so: unused DT entry: type 0x6fffffff arg 0x2
    11-11 05:42:27.171 11888-11907/ln.uiimagefirebase W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
    11-11 05:42:27.189 11888-11907/ln.uiimagefirebase W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
    11-11 05:42:27.195 11888-11907/ln.uiimagefirebase W/ResourcesManager: Asset path ‘/system/framework/com.android.media.remotedisplay.jar’ does not exist or contains no resources.
    11-11 05:42:27.195 11888-11907/ln.uiimagefirebase W/ResourcesManager: Asset path ‘/system/framework/com.android.location.provider.jar’ does not exist or contains no resources.
    11-11 05:42:27.289 11888-11888/ln.uiimagefirebase I/FA: App measurement is starting up, version: 9877
    11-11 05:42:27.289 11888-11888/ln.uiimagefirebase I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
    11-11 05:42:27.296 11888-11888/ln.uiimagefirebase I/FA: To enable faster debug mode event logging run:
    adb shell setprop firebase.analytics.debug-mode ln.uiimagefirebase
    11-11 05:42:27.374 11888-11888/ln.uiimagefirebase I/FirebaseInitProvider: FirebaseApp initialization successful
    11-11 05:42:27.590 11888-11888/ln.uiimagefirebase I/DynamiteModule: Considering local module com.google.android.gms.firebase_database:4 and remote module com.google.android.gms.firebase_database:4
    11-11 05:42:27.590 11888-11888/ln.uiimagefirebase I/DynamiteModule: Selected remote version of com.google.android.gms.firebase_database, version >= 4
    11-11 05:42:27.600 11888-11888/ln.uiimagefirebase E/System: stat file error, path is /data/data/com.google.android.gms/app_chimera/m/00000009/n/arm64-v8a, exception is android.system.ErrnoException: stat failed: ENOENT (No such file or directory)
    11-11 05:42:27.676 11888-11921/ln.uiimagefirebase D/libc-netbsd: [getaddrinfo]: hostname=firenotification-3382b.firebaseio.com; servname=(null); cache_mode=(null), netid=0; mark=0
    11-11 05:42:27.676 11888-11921/ln.uiimagefirebase D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0
    11-11 05:42:27.676 11888-11921/ln.uiimagefirebase D/libc-netbsd: [getaddrinfo]: hostname=firenotification-3382b.firebaseio.com; servname=(null); cache_mode=(null), netid=0; mark=0
    11-11 05:42:27.676 11888-11921/ln.uiimagefirebase D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=1024; ai_family=0
    11-11 05:42:27.679 11888-11921/ln.uiimagefirebase D/libc-netbsd: getaddrinfo: firenotification-3382b.firebaseio.com get result from proxy >>
    11-11 05:42:27.679 11888-11921/ln.uiimagefirebase I/System.out: propertyValue:true
    11-11 05:42:27.680 11888-11921/ln.uiimagefirebase I/System.out: [CDS]connect[firenotification-3382b.firebaseio.com/104.198.141.75:443] tm:90
    11-11 05:42:27.722 11888-11888/ln.uiimagefirebase W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
    11-11 05:42:28.247 11888-11924/ln.uiimagefirebase E/GED: Failed to get GED Log Buf, err(0)
    11-11 05:42:28.247 11888-11924/ln.uiimagefirebase I/OpenGLRenderer: Initialized EGL, version 1.4
    11-11 05:42:28.325 11888-11924/ln.uiimagefirebase W/MALI: glDrawArrays:714: [MALI] glDrawArrays takes more than 5ms here. Total elapse time(us): 6840
    11-11 05:42:28.523 11888-11921/ln.uiimagefirebase E/NativeCrypto: ssl=0x7f6fc7fd00 cert_verify_callback x509_store_ctx=0x7f5ddc21c8 arg=0x0
    11-11 05:42:28.523 11888-11921/ln.uiimagefirebase E/NativeCrypto: ssl=0x7f6fc7fd00 cert_verify_callback calling verifyCertificateChain authMethod=DHE_RSA
    11-11 05:42:29.161 11888-11921/ln.uiimagefirebase I/System.out: gba_cipher_suite:TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
    11-11 05:42:29.161 11888-11921/ln.uiimagefirebase D/libc-netbsd: [getaddrinfo]: hostname=firenotification-3382b.firebaseio.com; servname=(null); cache_mode=(null), netid=0; mark=0
    11-11 05:42:29.161 11888-11921/ln.uiimagefirebase D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0
    11-11 05:42:29.497 11888-11921/ln.uiimagefirebase I/System.out: [CDS]close[34827]
    11-11 05:42:29.497 11888-11921/ln.uiimagefirebase I/NetworkManagementSocketTagger: untagSocket(34)
    11-11 05:42:29.505 11888-11949/ln.uiimagefirebase D/libc-netbsd: [getaddrinfo]: hostname=s-usc1c-nss-105.firebaseio.com; servname=(null); cache_mode=(null), netid=0; mark=0
    11-11 05:42:29.505 11888-11949/ln.uiimagefirebase D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0
    11-11 05:42:29.505 11888-11949/ln.uiimagefirebase D/libc-netbsd: [getaddrinfo]: hostname=s-usc1c-nss-105.firebaseio.com; servname=(null); cache_mode=(null), netid=0; mark=0
    11-11 05:42:29.505 11888-11949/ln.uiimagefirebase D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=1024; ai_family=0
    11-11 05:42:29.507 11888-11949/ln.uiimagefirebase D/libc-netbsd: getaddrinfo: s-usc1c-nss-105.firebaseio.com get result from proxy >>
    11-11 05:42:29.507 11888-11949/ln.uiimagefirebase I/System.out: propertyValue:true
    11-11 05:42:29.507 11888-11949/ln.uiimagefirebase I/System.out: [CDS]connect[s-usc1c-nss-105.firebaseio.com/104.197.24.164:443] tm:90
    11-11 05:42:30.445 11888-11949/ln.uiimagefirebase E/NativeCrypto: ssl=0x7f6fc7fd00 cert_verify_callback x509_store_ctx=0x7f5ddc21c8 arg=0x0
    11-11 05:42:30.449 11888-11949/ln.uiimagefirebase E/NativeCrypto: ssl=0x7f6fc7fd00 cert_verify_callback calling verifyCertificateChain authMethod=ECDHE_RSA
    11-11 05:42:31.081 11888-11949/ln.uiimagefirebase I/System.out: gba_cipher_suite:TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
    11-11 05:42:31.081 11888-11949/ln.uiimagefirebase D/libc-netbsd: [getaddrinfo]: hostname=s-usc1c-nss-105.firebaseio.com; servname=(null); cache_mode=(null), netid=0; mark=0
    11-11 05:42:31.081 11888-11949/ln.uiimagefirebase D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0
    11-11 05:42:32.437 11888-11899/ln.uiimagefirebase W/art: Suspending all threads took: 21.825ms
    11-11 05:42:32.521 11888-11888/ln.uiimagefirebase W/SettingsInterface: Setting airplane_mode_on has moved from android.provider.Settings.System to android.provider.Settings.Global, returning read-only value.
    11-11 05:42:32.543 11888-11975/ln.uiimagefirebase I/System.out: url:https://www.google.co.in/search?q=hello&hl=en-US&source=lnms&prmd=mivn&tbm=isch&sa=X&ved=0ahUKEwjg9ozpzpzQAhVKpY8KHbJ-D5sQ_AUICCgC&biw=360&bih=567#imgrc=iomKndCSemKr5M%3A
    11-11 05:42:32.544 11888-11975/ln.uiimagefirebase I/System.out: open:https://www.google.co.in/search?q=hello&hl=en-US&source=lnms&prmd=mivn&tbm=isch&sa=X&ved=0ahUKEwjg9ozpzpzQAhVKpY8KHbJ-D5sQ_AUICCgC&biw=360&bih=567#imgrc=iomKndCSemKr5M%3A
    11-11 05:42:32.544 11888-11888/ln.uiimagefirebase E/AndroidRuntime: FATAL EXCEPTION: main
    Process: ln.uiimagefirebase, PID: 11888
    java.lang.IllegalArgumentException: Path must not be empty.
    at com.squareup.picasso.Picasso.load(Picasso.java:297)
    at ln.uiimagefirebase.MainActivity$1.populateViewHolder(MainActivity.java:72)
    at ln.uiimagefirebase.MainActivity$1.populateViewHolder(MainActivity.java:64)
    at com.firebase.ui.database.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:177)
    at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6062)
    at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6095)
    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5277)
    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5153)
    at android.support.v7.widget.LayoutState.next(LayoutState.java:100)
    at android.support.v7.widget.StaggeredGridLayoutManager.fill(StaggeredGridLayoutManager.java:1568)
    at android.support.v7.widget.StaggeredGridLayoutManager.onLayoutChildren(StaggeredGridLayoutManager.java:678)
    at android.support.v7.widget.StaggeredGridLayoutManager.onLayoutChildren(StaggeredGridLayoutManager.java:600)
    at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3374)
    at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3183)
    at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1593)
    at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:323)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:800)
    at android.view.Choreographer.doCallbacks(Choreographer.java:603)
    at android.view.Choreographer.doFrame(Choreographer.java:571)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:786)
    at android.os.Handler.handleCallback(Handler.java:815)
    at android.os.Handler.dispatchMessage(Handler.java:104)
    at android.os.Looper.loop(Looper.java:194)
    at android.app.ActivityThread.main(ActivityThread.java:5847)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1010)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
    11-11 05:42:32.549 11888-11975/ln.uiimagefirebase D/libc-netbsd: [getaddrinfo]: hostname=www.google.co.in; servname=(null); cache_mode=(null), netid=0; mark=0
    11-11 05:42:32.549 11888-11975/ln.uiimagefirebase D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0
    11-11 05:42:32.549 11888-11975/ln.uiimagefirebase D/libc-netbsd: [getaddrinfo]: hostname=www.google.co.in; servname=(null); cache_mode=(null), netid=0; mark=0
    11-11 05:42:32.549 11888-11975/ln.uiimagefirebase D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=1024; ai_family=0
    11-11 05:42:32.576 11888-11888/ln.uiimagefirebase I/Process: Sending signal. PID: 11888 SIG: 9

  • Stas

    Hi there! Thank you for this tutorial, it was helpful. But here is what I’m struggling with: I’ve actually inserted this tutorial material into my simple app where I have a login option. So here is the problem – when I logout and then login again All the data vanishes from the app, while they are still nicely present in firebase. So my question is does anybody know how to fix this? How to make data stay both in firebase and application? And I also noticed that after logout my app doesn’t recognise the user and stores new data to firebase like this is a new user (with different unique key). Thanks ahead, guys!

  • Maaz Patel

    Hi ravi ,

    I am getting permission denied exception:

    com.google.firebase.database.DatabaseException: Firebase Database error: Permission denied

    • Tyo Gunawan

      check your rules in firebase database again, make sure like this

      “rules”: {
      “.read”: true,
      “.write”: true
      }

  • vikash kumar

    thanks ,it’s really very usefull.

  • Danish Khan

    Assalam O Alaikum I have a little request would you like to make a tutorial on how to make foam with fields and image by using firebase

  • Abdul Aziz

    thanks a lot, it so usefull

  • hi ravi, thanks for nice post.
    but, i don’t understand, why we should use an annotation @IgnoreExtraProperties in model ?

  • Abhishek Sharma

    Hiii Ravi, Mujhe Jab bhi Koi Problem Hoti Hai Mai Hamesha Sirf ek hi site par Jata hu androidhive.info
    Thank U very Much brother for all the tutorials.

  • Harish

    Hi Ravi,
    Awesome blog for android developers. I have learnt so many things from your blog.

    I have one question don’t no how to approach.
    I want to download and upload images parallel in my app like whats app. How to do that?
    I need to use AsycTask or InentService and what are the consequences like if network goes,or if we are using 2g,3g connections.? if one download fails everything fails.. lot of doubts..please can you write blog on that or
    Can you send code regarding that. It will be very helpfull

  • Cancerian boy

    Hi @ravi8x:disqus Ravi Tamada , Sir kindly help me , I want to parse real time data from thingspeak to my mobile application . Please tell me about this .

  • pranjit bharali

    Hi @ravi8x:disqus , I am doing everything as instructed in firebase docs. I am not able to read as well as write in the database… neither it is showing any king of error… What can be the reason for this ?

    • Have you added correct google-services.json ? Make sure that app is connected for correct firebase app.

      • pranjit bharali

        yes. I did.

        I change the read and write rule for unauthenticated users too.

        Really stuck with this … Don’t know what the error is.. !!

        • pranjit bharali

          And one more point I could able to create the authentication system with the same app and it’s working. But database is not connecting… !!

          • Can you paste a sample code that stores a string value to database.

  • pradnyoday

    can you add the code for retriving data for a specific user?

  • Kunal Verma

    Hi @ravi8x:disqus, Great Turorial helps me a lot to understand firebase. I am new in android as well as in firebase, I need to create a collaborative whitebaord application in android and upon my research I found that firebase is great for such application. Can you please add a small tutorial on how to create collaborative whieboard using firebase in android please? much appriceated.

    Thanks!
    Kunal

  • taufan99

    Thanks for the tutorial, Sir, but there is something that bugs me a lot.

    Whenever I press the Save button, I have to do it twice to be able to save the data, and whenever I do, it always shows an error message, but the data itself gets saved without a notification that the data has been saved to the database.

    Perhaps I need to do something?

  • Bala Aditya

    Hi Ravi Tamada, Great Tutorial helps me a lot to understand firebase. I built an app for android which is working fine, now i want to use the same firebase database to ios app. could you share it if know how to do it. Thanks in Advance.

  • Ryan Andrew Ortiz Biugos

    I got VerifyError. how can I fix this ?

  • Monil Gupta

    Hi Sir,

    Firebase database is working with Activity.xml file.
    But if i implement it with only java file , then Firebase Database is not working.
    Is there any logic behind it or how can we made it working with only java file.
    Because my whole code is in DataParser.java file which doesnot have xml file

    Not working

    public class NewJavaClass extends MainActivity {

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference(“message”);

    myRef.setValue(“Hello, World!”);
    }

    In MainActivity.java class , its working

    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    EditText et1;
    Button b1;
    DatabaseReference databaseReference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    et1 = (EditText)findViewById(R.id.editText);
    b1 = (Button)findViewById(R.id.button);
    b1.setOnClickListener( this);

    }

    @Override
    public void onClick(View v) {
    String name = et1.getText().toString();

    databaseReference = FirebaseDatabase.getInstance().getReference();
    String id = databaseReference.push().getKey();

    Feeding feeding = new Feeding(name);
    databaseReference.child(id).setValue(feeding);
    Intent i2 = new Intent(getApplicationContext(),FirebaseTesting.class);
    startActivity(i2);

    }

    }

  • Maranatha Box

    Hello, I want to
    ask. The Login Login project and relatime database I have combined. But
    when saving in the database user UID is in lgin not the same as the
    realtime database. How to order the same? Thanks

    • Justine Lance T. Mojal

      Try checking the variables used to store it.

  • Nikhil

    Hi Ravi.
    I want to know what happen if my app get download by more than 100 users ?

    • Justine Lance T. Mojal

      You’ll have to pay to continue using the services.

  • Divy Shah

    Hey , I want to make a app which display the live rates of currency,commodity.So for that i have to pass multiple JSON url. Can you tell me How to parse multiple data in android??

  • Nice read through related to comprehending Firebase and it serves to be a useful portal for others to be enriched with the knowledge of Firebase and the related topics. Good posting !!

  • Daniel Ekpo

    Thanks a lot for this tutorial. You have a way of explaining things in a really straightforward way.

  • Zar Ni

    Very nice and straightforward tutorial. Thanks Sir Ravi !