Android Firebase - ListView - Save,Retrieve,Show

android crud

So lets cover android firebase listview example.How to save from edittext,retrieve that particular data and of course show in a simple listview.

ListView is one of the most popular adapterviews while Firebase is probably the most popular database backend service currently in the market.

These two are easy to use and provides us with powerful opportunities to create amazing apps.

The Plan

This android firebase listview tutorial.This is what we do :

  • Save from edittext to google firebase database using methods setValue() and push();
  • Fetch that particular data by attaching a childEventListener to a databaseReference instance.
  • Read the children of a dataSnapshot.
  • Fill Simple ArrayList
  • Bind the arraylist to ListView

What Is Firebase Realtime Database?

Firebase Realtime database is a database backend as a service Cloud hosted solution that gives us the platform to build rich apps.Normally we are used to making HTTP requests to read or write data against our servers.But not in Firebase.It uses synchronization technology that allows it to be realtime,but still performant.

Main Feautures of Firebase Realtime DB

No. Feature
1. Its realtime.
2. Platfrom Independent.
3. Easy Access Control.
4. It’s a NoSQL solution and is heavily optimized for performance.
5. Has Offline capability.
6. Its User Friendly.

Let's go.

1. Create Basic Activity Project

  1. First create a new project in android studio. Go to File --> New Project.

  2. Type the application name and choose the company name. New Project Dialog

  3. Choose minimum SDK. Choose minimum SDK

  4. Choose Basic activity. Choose Empty Activity

  5. Click Finish. Finish

Basic activity will have a toolbar and floating action button already added in the layout

Normally two layouts get generated with this option:

No. Name Type Description
1. activity_main.xml XML Layout Will get inflated into MainActivity Layout.Typically contains appbarlayout with toolbar.Also has a floatingactionbutton.
2. content_main.xml XML Layout Will be included into activity_main.xml.You add your views and widgets here.
3. Class Main Activity.

In this example I used a basic activity.

The activity will automatically be registered in the android_manifest.xml. Android Activities are components and normally need to be registered as an application component.

If you've created yours manually then register it inside the <application>...<application> as following, replacing the MainActivity with your activity name:

        <activity android:name=".MainActivity">


                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />



You can see that one action and category are specified as intent filters. The category makes our MainActivity as launcher activity. Launcher activities get executed first when th android app is run.

Advantage of Creating Basic Activity project

You can optionally choose empty activity over basic activity for this project.

However basic activity has the following advantages:

No. Advantage
1. Provides us a readymade toolbar which gives us actionbar features yet easily customizable
2. Provides us with appbar layout which implements material design appbar concepts.
3. Provides a FloatinActionButton which we can readily use to initiate quick actions especially in examples like these.
4. Decouples our custom content views and widgets from the templating features like toolbar.

Generated Project Structure

AndroidStudio will generate for you a project with default configurations via a set of files and directories.

Here are the most important of them:

No. File Major Responsibility
1. build/ A directory containing resources that have been compiled from the building of application and the classes generated by android tools. Such a tool is the file. file normally holds the references to application resources.
2. libs/ To hold libraries we use in our project.
3. src/main/ To hold the source code of our application.This is the main folder you work with.
4. src/main/java/ Contains our java classes organized as packages.
5. src/main/res/ Contains our project resources folders as follows.
6. src/main/res/drawable/ Contains our drawable resources.
7. src/main/res/layout/ Contains our layout resources.
8. src/main/res/menu/ Contains our menu resources XML code.
9. src/main/res/values/ Contains our values resources XML code.These define sets of name-value pairs and can be strings, styles and colors.
10. AndroidManifest.xml This file gets autogenerated when we create an android project.It will define basic information needed by the android system like application name,package name,permissions,activities,intents etc.
11. build.gradle Gradle Script used to build the android app.

2. Create Firebase and Download Configuration File

Head over to Firebase Console, create a Firebase App, Register your app id and download the google-services.json file. Add it to your app folder.

Add Config File

3. Add Google services classpath and maven url

Add classpath ''. This you do in the project level build.gradle. You may use later versions.

Also add the google maven url in you respositories. Firebase will be fetched from that url.

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
    dependencies {
        classpath ''
        classpath ''

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files

allprojects {
    repositories {
        maven {
            url "" // Google's Maven repository

task clean(type: Delete) {
    delete rootProject.buildDir

4. Add Firebase Dependencies

Add FirebaseDatabase dependencies in your app level build.gradle. You may use later versions than me. Then sync the project to download them and add them as part of your project.

apply plugin: ''

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.tutorials.hp.firebasesimplelistview"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), ''

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile ''
    compile ''

    compile ''
    compile ''
apply plugin: ''

Make sure you apply plugin: '' as above.

5. Create User Interface

User interfaces are typically created in android using XML layouts as opposed by direct java coding.

This is an example fo declarative programming.

######### Advantages of Using XML over Java

No. Advantage
1. Declarative creation of widgets and views allows us to use a declarative language XML which makes is easier.
2. It's easily maintanable as the user interface is decoupled from your Java logic.
3. It's easier to share or download code and safely test them before runtime.
4. You can use XML generated tools to generate XML

Here are our layouts for this project:

(a). activity_main.xml
  • This layout gets inflated to MainActivity user interface.
  • It includes the content_main.xml.

Here are some of the widgets, views and viewgroups that get employed"

No. View/ViewGroup Package Role
1. CordinatorLayout Super-powered framelayout that provides our application's top level decoration and is also specifies interactions and behavioros of all it's children.
2. AppBarLayout A LinearLayout child that arranges its children vertically and provides material design app bar concepts like scrolling gestures.
3. ToolBar < A ViewGroup that can provide actionbar features yet still be used within application layouts.
4. FloatingActionButton An circular imageview floating above the UI that we can use as buttons.
<?xml version="1.0" encoding="utf-8"?>
< xmlns:android=""


            app:popupTheme="@style/AppTheme.PopupOverlay" />


    <include layout="@layout/content_main" />

        android:src="@android:drawable/ic_dialog_email" />

(b). content_main.xml

This layout will get interpolated into our activity_main.xml.

Here are the roles of this layout:

No. Responsibility
1. Define a ListView identified by a unique id. That ListView is our adapterview and will render our realtime data from Firebase.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""

(c). input_dialog.xml
  • InputDialog.xml

This is our input form layout.

Here are it's roles:

No. Responsibility
1. Define an EditText for writing data to firebase. Wrap that edittext in a TextInputLayout to give it a material design feel.
2. Define a Button to be used as our action button to for saving data to firebase.
3. Align all these widgets in a vertical manner with the help of a LinearLayout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" android:layout_width="match_parent"



                android:hint= "Name" />

        <Button android:id="@+id/saveBtn"



6. Our Model Class :

  • Data object
  • Represents a single spacecraft and its properties.

It has the following responsibilities:

No. Responsibility
1. Define one private field which will be the sole property of our spacecraft. That is : name property.
2. Define one empty constructor which is require by Firebase.
3. Expose our instance field for modification or data retrieval via setter and getter methods respectively.
package com.tutorials.hp.firebasesimplelistview.m_Model;

public class Spacecraft {

    String name;

    public Spacecraft() {

    public String getName() {
        return name;

    public void setName(String name) { = name;

7. Our FirebaseHelper class

  • Perform basic Write to Firebase database
  • Read from Firebase database.
  • Fill simple arraylist

Here are the major responsibilities of this class:

No. Responsibility
1. Maintain three instance fields: a DatabaseReference, a Boolean and an ArrayList.
2. Obtain a DatabaseReference via the parameter from outside and assign it to the one we maintain locally.
3. Define a public method save() that receives a Spacecraft object, then attempt to save it to Firebase and return either true or false based on the success. To save data we use db.child("Spacecraft").push().setValue(spacecraft).
4. Define a private helper method called fetchData() that receives a object. Then loop through the children of this DataSnapshot getting the value of each DataSnapshot child via datasnapshotChild.getValue(Spacecraft.class). Add these values into our private ArrayList.
5. Define a method retrieve(). Add child event listeners to our private DatabaseReference we had maintained. When any DataSnapshot child changes or gets added, call our fetchData() passing in that DataSnapshot as a parameter. This is how fetch data. Then return the filled arraylist.
package com.tutorials.hp.firebasesimplelistview.m_FireBase;

import com.tutorials.hp.firebasesimplelistview.m_Model.Spacecraft;

import java.util.ArrayList;

public class FirebaseHelper {

    DatabaseReference db;
    Boolean saved=null;
    ArrayList<String> spacecrafts=new ArrayList<>();

    public FirebaseHelper(DatabaseReference db) {
        this.db = db;

    public Boolean save(Spacecraft spacecraft)

            }catch (DatabaseException e)

        return saved;

    public ArrayList<String> retrieve()
        db.addChildEventListener(new ChildEventListener() {
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {

            public void onChildChanged(DataSnapshot dataSnapshot, String s) {


            public void onChildRemoved(DataSnapshot dataSnapshot) {


            public void onChildMoved(DataSnapshot dataSnapshot, String s) {


            public void onCancelled(DatabaseError databaseError) {


        return spacecrafts;

    private void fetchData(DataSnapshot dataSnapshot)

        for (DataSnapshot ds : dataSnapshot.getChildren())
            String name=ds.getValue(Spacecraft.class).getName();

8. Our MainActivity class

  • Launcher activity
  • Where we bind to listview to our data using arrayadapter
  • Initialize DatabaseReference
  • Show input dialog

It derives from

Here are it's major responsibilities:

No. Responsibility
1. Allow itself to become an android activity component by deriving from
2. Listen to activity creation callback by overrding the onCreate() method.
3. Invoke the onCreate() method of the parent Activity class and tell it of a Bundle we've received.
4. Inflate the activity_main.xml into a View object and set it as the content view of this activity.
5. Search for a toolbar by it's id and set it as our actionbar.
6. Host an input dialog that will be used to save data into Firebase Realtime database.
7. Search for the EditText and Button from our layout and return them as view objects.These widgets will help users perform this data insertion. This by saving data from these EditTexts when the save button is clicked.
8. Find ListView by its id from our layouts.
9. Obtain a instance then obtain a DatabaseReference from that instance then assign it to our local DatabaseReference private field.
10. Instantiate our CustomAdapter, pass it our data then set the adapter to our ListView.
11. Reference our FloatingActionButton from our activity_main.xml, then listen to its onClick events, then when it's clicked display our input Dialog.
package com.tutorials.hp.firebasesimplelistview;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.tutorials.hp.firebasesimplelistview.m_FireBase.FirebaseHelper;
import com.tutorials.hp.firebasesimplelistview.m_Model.Spacecraft;

public class MainActivity extends AppCompatActivity {

    ListView lv;
    ArrayAdapter<String> adapter;
    DatabaseReference db;
    FirebaseHelper helper;

    protected void onCreate(Bundle savedInstanceState) {
        Toolbar toolbar = (Toolbar) findViewById(;

        lv= (ListView) findViewById(;

        db= FirebaseDatabase.getInstance().getReference();
        helper=new FirebaseHelper(db);

        adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,helper.retrieve());

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, helper.retrieve().get(position), Toast.LENGTH_SHORT).show();

        FloatingActionButton fab = (FloatingActionButton) findViewById(;
        fab.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

    private void displayInputDialog()
        Dialog d=new Dialog(this);
        d.setTitle("Save To Firebase");

        final EditText nameEditTxt= (EditText) d.findViewById(;
        Button saveBtn= (Button) d.findViewById(;

        saveBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                //GET DATA
                String name=nameEditTxt.getText().toString();

                //SET DATA
                Spacecraft s=new Spacecraft();

                if(name.length()>0 && name != null)
                        adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,helper.retrieve());

                    Toast.makeText(MainActivity.this, "Name cannot be empty", Toast.LENGTH_SHORT).show();



9. AndroidManifest.xml

  • Add this to your androidmainfest.xml file. This because to access Firebase we need internet connection hence we have to specify a permission. Add it under the .. tag.
    <uses-permission android:name="android.permission.INTERNET"/>

How To Run

  1. Download the project.
  2. You'll get a zipped file,extract it.
  3. Open the Android Studio.
  4. Now close, already open project.
  5. From the Menu bar click on File >New> Import Project.
  6. Now Choose a Destination Folder, from where you want to import project.
  7. Choose an Android Project.
  8. Now Click on “OK“.
  9. Done, your done importing the project,now edit it.
  10. You'll need to head over to Firebase Console, create app, then download configuration file and add to your project in the app folder.You also have to allow writes and reads from the FirebaseDatabase without authentication.

More Resources

Resource Link
GitHub Browse Browse
GitHub Download Link Download

Best Regards, Oclemy.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:


What do You Think

Previous Post Next Post