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. 

Categories: AndroidTutorials

Subscribe and get a free eBook on 8 Tips to level up your Android Development Skills.

(We hate spam as much as you do)

You have Successfully Subscribed!

%d bloggers like this: