Android Display List View from Firebase Database

This is a beginners guide to use Firebase Realtime Database in Android. Firebase is backend as a service which provides easy to use services like realtime database, storage, authentication of users.

In this article we will see how we can use Firebase database to fetch real time data and present in our Android app. Firebase Database is cloud hosted no sql database. Data is synced and can be cached across all devices in realtime. Since it is a realtime cloud database, any changes or updates in the database are reflected in realtime across all the client devices.

We will see how we can display a list of items in Android fetched from firebase database.

Android Setup

  • Create a new android project with empty activity.
  • Open Tools -> Firebase

Android studio firebase connection setup

  • In the Firebase Assistant window click on Realtime Database
  • Click on Save and retrieve data
  • In the next window click on Connect to Firebase

If this is the first time you are setting firebase then connect to firebase will open an authentication window in browser. Go ahead and authenticate

 

 

  • Once authenticated click on Connect to Firebase again to create a new Firebase project.
  • Click on Add the realtime database to your app button in firebase database assistant.

After updating the project build.gradle should have firebase database dependency.

Firebase Database Setup

  • Open firebase console and select newly created firebase project
  • Click database and select realtime database. For simplicity you can select Start in test mode. Let me know in comments if you want to know how to secure your database.
  • For this example I have created a json file that you can import in your database.  Download Targetapi.json

Android Client Code

Pojo Class

Main Activity

Adapter Class

activity_main.xml layout

Row layout target_row.xml

Build and run the project. This will display the list saved in realtime database in android recycler view.

Any update in the database data will call ValueEventListener again and the list will refresh automatically.

Enable persistance (Offline usage)

Firebase has a very beautiful feature which is to cache the the data retrieved from the cloud database for offline usage. To enable persistent database enable firebase database persistent flag in Application class.

Extend Application class and add class name in AndroidManifest application tag.

Updated AndroidManifest.xml

 

Leave a Reply

%d bloggers like this: