Knowband Blog | Ecommerce Modules

How to fetch data from Firebase in Android?

Objectives of the blog

After reading this blog we will be able to fetch data from Firebase Realtime Database. This data may include simple data types, such as Strings, or complex data types such as Java objects.

Pre-requisites

We need to have a Android Studio project and Firebase project ready in order to use the Firebase Realtime Database. Create a new Android Studio project (or use any existing project). This Android Studio project will be used for working with the realtime database.

Follow the steps given below to create the Firebase project –

1. Go to https://console.firebase.google.com

2. Click on “Add Project” button.

3. Enter the Project name and accept the conditions and click on “Continue” button.

 

4. Then add Android app to your project. It requires entering the package name of the app. Click on Next.

5. Download the google-services.json file, and move this file to the location in the Android project in Android Studio as specified on the screen.

6. In the next step, there would be a small tutorial to add 3 lines of code in the project-level and app-level build.gradle files. Add them accordingly.

7. Then finish this process of adding the Android app to the project.

8. Then click on “Database” option from the left menu, and click on “Create Database” button.

 

 

9. Firebase setup is completed

Now add the Firebase library for using the Firebase Realtime Database in the app-level build.gradle file. This can be done by adding the following line:

implementation 'com.google.firebase:firebase-database:16.0.6'

Code Implementation

A Firebase reference points to a location in Firebase Database where data is stored. Even if you create multiple references, they all share the same connection provided you used the same path while creating the reference from the database instance.

Firstly we need to have an instance of the Firebase Database in order to use it. The instance can be created by the following line of code.

 

private FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();

 

Now there is need to create references of the paths where the data is stored in the database. As the data in the Firebase database is stored in the JSON format, the keys of the JSON object are the paths specified in the references.

The reference to the root node can be created by the following line of code:

 

private DatabaseReference mGetReference = mDatabase.getReference();

 

After getting the reference of the database, an asynchronous listener has to be attached to the database reference which actively listens to any change done in the database. This listener returns a data snapshot of the database initially for the first time when it is attached. Then the data snapshot is returned when any change is done at the path where the database reference is pointing to.

Usually, the database contains same type of data, but suppose the database contains some data of different types. Below find the screenshot of the database containing some dummy data:

 

To fetch the database from this database, attach the ValueEventListener to the database reference. The listener can be added by the following code:

 

mGetReference.addValueEventListener(new ValueEventListener() {
   @Override
   public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
 
       if (dataSnapshot.exists()){
           HashMap<String, Object> dataMap = (HashMap<String, Object>) dataSnapshot.getValue();
 
           for (String key : dataMap.keySet()){
 
               Object data = dataMap.get(key);
 
               try{
                   HashMap<String, Object> userData = (HashMap<String, Object>) data;
 
                   User mUser = new User((String) userData.get("name"), (int) (long) userData.get("age"));
                   addTextToView(mUser.getName() + " - " + Integer.toString(mUser.getAge()));
 
               }catch (ClassCastException cce){
 
// If the object can’t be casted into HashMap, it means that it is of type String.  
 
                   try{
 
                       String mString = String.valueOf(dataMap.get(key));
                       addTextToView(mString);
 
                   }catch (ClassCastException cce2){
 
                   }
               }
 
           }
       }
   }
 
   @Override
   public void onCancelled(@NonNull DatabaseError databaseError) {
 
   }
});

After attaching the listener, it is executed first initially returning all the data in the database at that time. This listener will be later invoked at the time when any change takes place in the database at the path pointed by the reference the listener is attached to.

Summary

After following the above procedure, you will be able to fetch data from the Firebase Realtime database in Android.

If you face any issues, please feel free to reach us at support@knowband.com.  We also provide custom development and modules for major CMS platforms like Prestashop, Opencart, Magento, Magento 2 and Woocommerce.

Take a look at our most popular Woocommerce No Code Mobile App builder: