Open In App

How to Retrieve Data from Firebase Realtime Database in Android ListView?

Last Updated : 15 Jan, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Firebase Realtime Database provides us a feature to give Real-time updates to your data inside your app within milli-seconds. With the help of Firebase, you can provide Real-time updates to your users. In this article, we will take a look at the implementation of the Firebase Realtime Database for our ListView in Android. In this ListView, we will be able to add and remove the list items on a real-time basis. So let’s move towards the implementation of our Firebase Realtime Database in ListView. 

What we are going to build in this article? 

We will be creating a simple application in which we will be creating a ListView and inside that ListView, we will be fetching the data from our Firebase Realtime database. From Firebase we can update or delete our list items according to our requirements and the data will be updated on a real-time basis. Note that we are going to implement this project using the Java language. 

Step by Step Implementation

Step 1: Create a new Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Connect your app to Firebase

After creating a new project. Navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot.  

Inside that column Navigate to Firebase Realtime Database. Click on that option and you will get to see two options on Connect app to Firebase and Add Firebase Realtime Database to your app. Click on Connect now and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase.  

After completing this process you will get to see the below screen.  

Now verify that your app is connected to Firebase or not. Go to your build.gradle file. Navigate to the app > Gradle Scripts > build.gradle file and make sure that the below dependency is added in your dependencies section.  

implementation ‘com.google.firebase:firebase-database:19.6.0’

If the above dependency is not added in your dependencies section. Add this dependency and sync your project. Now we will move towards the XML part of our app. 

Step 3: Working with the activity_main.xml file

Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <!--ListView for displaying 
        our list of courses-->
    <ListView
        android:id="@+id/idLVCourses"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
  
</RelativeLayout>


Step 4: Add internet permission in your AndroidManifest.xml file

Add the permission for the internet in the AndroidManifest.xml file. 

XML




<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


Step 5: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
  
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
  
import com.google.firebase.database.ChildEventListener;
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 java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
  
    // creating variables for our list view.
    private ListView coursesLV;
      
    // creating a new array list.
    ArrayList<String> coursesArrayList;
      
    // creating a variable for database reference.
    DatabaseReference reference;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing variables for listviews.
        coursesLV = findViewById(R.id.idLVCourses);
          
        // initializing our array list
        coursesArrayList = new ArrayList<String>();
          
        // calling a method to get data from
        // Firebase and set data to list view
        initializeListView();
    }
  
    private void initializeListView() {
        // creating a new array adapter for our list view.
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, coursesArrayList);
  
        // below line is used for getting reference
        // of our Firebase Database.
        reference = FirebaseDatabase.getInstance().getReference();
         
        // in below line we are calling method for add child event 
        // listener to get the child of our database.
        reference.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
                // this method is called when new child is added to 
                // our data base and after adding new child
                // we are adding that item inside our array list and
                // notifying our adapter that the data in adapter is changed.
                coursesArrayList.add(snapshot.getValue(String.class));
                adapter.notifyDataSetChanged();
            }
  
            @Override
            public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
                // this method is called when the new child is added.
                // when the new child is added to our list we will be 
                // notifying our adapter that data has changed.
                adapter.notifyDataSetChanged();
            }
  
            @Override
            public void onChildRemoved(@NonNull DataSnapshot snapshot) {
                // below method is called when we remove a child from our database.
                // inside this method we are removing the child from our array list 
                // by comparing with it's value.
                // after removing the data we are notifying our adapter that the 
                // data has been changed.
                coursesArrayList.remove(snapshot.getValue(String.class));
                adapter.notifyDataSetChanged();
            }
  
            @Override
            public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
                // this method is called when we move our 
                // child in our database.
                // in our code we are note moving any child.
            }
  
            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                // this method is called when we get any 
                // error from Firebase with error.
            }
        });
        // below line is used for setting 
        // an adapter to our list view.
        coursesLV.setAdapter(adapter);
    }
}


After adding this code to your app. Now go to Firebase and click on Go to console option which is on the top right corner.  

After clicking on this screen you will get to see the below screen with your all project inside that select your project.  

Inside that screen click n Realtime Database in the left window.  

After clicking on this option you will get to see the screen on the right side. On this page click on the Rules option which is present in the top bar. You will get to see the below screen.  

In this project, we are adding our rules as true for reading as well as write because we are not using any authentication to verify our user. So we are currently setting it to true to test our application. After changing your rules. Click on the publish button at the top right corner and your rules will be saved there. Now again come back to the Data tab. Now we will be adding our data to Firebase manually from Firebase itself.

Step 6: Adding data in Firebase Console

Inside Firebase Database the parent node which we will get to see is a parent. Inside this parent, we have to add child items. This child item will be displayed inside our ListView. We will be adding new child items inside our Database. To add the data for our list view. We simply have to add an item by clicking on the “+” option on the right side and after that add the item inside our database. In a similar way add multiple items to your Database. These items will be displayed inside our ListView. 

The above mentioned is the image in which you will get to know How to add a single item in your listview. Similarly add multiple items in your Database and you will get to see the below screen. 

After adding this data run your app and see the output of the app. After running your app update the data in your Firebase. You can add, remove any child or update any child, you will get to see Realtime Updates in your ListView. 

Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads