In the last tutorial, I showed you how to add Email and Google Login using Firebase in an Android app. Today we are going to learn how to save and retrieve data from Firebase in Android.

The prerequisites

Before using Firebase Realtime Database, make sure that you have connected your Android app to Firebase. Now add the following Firebase Database dependency to your app level build.gradle file.

compile 'com.google.firebase:firebase-database:10.2.4'

If you get “Failed to resolve: com.google.firebase:firebase-database:10.2.0” error on syncing, follow this step to make things work.

Database access permissions

By default, read and write access to your database is restricted. So, only authenticated users can read or write data. So if you haven’t added an authentication system to your app, it’s the right time to do it. You can also change Firebase database rules that allow access to data without requiring authentication. But it is not recommended as it makes your database publicly accessible to anyone.

Saving Data to Firebase

Now let’s create an EditText in MainActivity that will take value from User and on clicking the submit button, the value will be saved to Firebase database.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:gravity="center">

    <EditText
        android:id="@+id/tvValue"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btnSubmit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="Submit"/>

</RelativeLayout>

The above code creates a design as shown below.

Firebase Realtime Database

Now let’s create a reference to the “demo” node in Firebase and push the value to this node when User clicks on Submit button. If a node is not present in Firebase database, making a reference and pushing the value automatically creates the node.

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class MainActivity extends AppCompatActivity {

    EditText editText;
    Button submit;
    DatabaseReference rootRef,demoRef;

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

        editText = (EditText) findViewById(R.id.etValue);
        submit = (Button) findViewById(R.id.btnSubmit);

        //database reference pointing to root of database
        rootRef = FirebaseDatabase.getInstance().getReference();

        //database reference pointing to demo node
        demoRef = rootRef.child("demo");

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String value = editText.getText().toString();

                //push creates a unique id in database
                demoRef.push().setValue(value);
            }
        });

    }
}

 

Now when you run the app and type something in EditText and then click on Submit button, you can see that value is saved to Firebase database as shown below.

Firebase Realtime Database

Retrieving data from Firebase

Not let’s add another button which will fetch the value from the database and display it in TextView. Add the below code in activity_main.xml file.

<Button
      android:id="@+id/btnFetch"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="Fetch"
      android:layout_below="@+id/btnSubmit"/>
  
<TextView
 android:id="@+id/tvValue"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_below="@+id/btnFetch"
 android:textSize="16dp"
 android:gravity="center_horizontal"/>

Now, in order to fetch the value from ‘demo’ node in Firebase, use the already created database reference pointing to ‘demo’ node and attach a ValueEventListener to it. To do so, add the following code in your MainActivity.java file.

fetch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                demoRef.child("value").addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                     String value = dataSnapshot.getValue(String.class);
                        demoValue.setText(value);
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                    }
                });
            }
        });

When you run the app and click on fetch button, you can see that the message “Welcome to TEC” is fetched from Firebase and displayed in TextView as shown below.

Firebase Realtime Database

In case you are facing some issues, I’m attaching the full code. Have a look

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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 {

    EditText editText;
    Button submit,fetch;
    DatabaseReference rootRef,demoRef;
    TextView demoValue;

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

        editText = (EditText) findViewById(R.id.etValue);
        demoValue = (TextView) findViewById(R.id.tvValue);
        submit = (Button) findViewById(R.id.btnSubmit);
        fetch = (Button) findViewById(R.id.btnFetch);

        //database reference pointing to root of database
        rootRef = FirebaseDatabase.getInstance().getReference();

        //database reference pointing to demo node
        demoRef = rootRef.child("demo");

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String value = editText.getText().toString();

                //push creates a unique id in database
                demoRef.child("value").setValue(value);
            }
        });

        fetch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                demoRef.child("value").addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                     String value = dataSnapshot.getValue(String.class);
                        demoValue.setText(value);
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                    }
                });
            }
        });
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:padding="16dp">

    <EditText
        android:id="@+id/etValue"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btnSubmit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/etValue"
        android:layout_marginTop="24dp"
        android:text="Submit" />

    <Button
        android:id="@+id/btnFetch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btnSubmit"
        android:text="Fetch" />

    <TextView
        android:id="@+id/tvValue"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btnFetch"
        android:gravity="center_horizontal"
        android:textSize="16dp" />

</RelativeLayout>

In the next tutorial, I will show you how to upload an image to Firebase Storage and show the uploaded image in ImageView. 

Kotlin for Android Developers

Categories: AndroidTutorials

  • Pingback: Upload an Image to Firebase Storage (Firebase Tutorial #4) - The Engineer's Cafe()

  • Rahul Soshte

    Thanks for the Tutorial!Dada!

    • The Engineer’s Cafe

      Anytime 🙂

  • tharun tamil

    how to add a class

  • Marvin Gorres

    how do you retrieve all child value if you have more than just one?

    • Use Iterable for that as shown below:

      mRef.addListenerForSingleValueEvent(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot dataSnapshot) {

      Iterable dataSnapshotIterable = dataSnapshot.getChildren();
      loadingIndicatorView.hide();

      for (DataSnapshot p : dataSnapshotIterable) {

      // Your code here

      }

  • I have Get the data by this but all in same tab so i have created more child like name and email,but i want to make every user data in new tab of users

  • Siphamandla Gcabashe

    Thanks for the tutorial but i have this one question, how to retrieve information that is stored in a database child by calling it in a class without pressing a button

    • You can write the code directly in onCreate method.

      • Siphamandla Gcabashe

        can i get back to you if i get stuck?

        • Yep. You can like our fb page and we can chat over there if you face any problem.

  • ahsan syed

    how can i retrieve specific data from root

    • First get the root reference
      DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();

      Now directly point to the key of the data you want
      DatabaseReference ref = rootRef.child(“yourKey”);

      Once done, fetch the value
      ref.addListenerForSingleValueEvent(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot dataSnapshot) {
      String value = dataSnapshot.getValue(String.class);

  • Sulaiman Abdul Quadeer

    I used the same code for retrieving data with a difference that I used the onCreate() method to retrieve and not the button but the data wasn’t retrieved.

  • Mon Dher

    I tried to open your source code but when i open your project error message indicate Missing google json file and then i added my json file and i received this error ” Error:Execution failed for task ‘:app:processDebugGoogleServices’.

    > No matching client found for package name ‘com.androidjson.firebase_androidjsoncom’

%d bloggers like this: