Open In App

Android Jetpack Compose – Retrieve Data From the Firebase Realtime Database

Improve
Improve
Like Article
Like
Save
Share
Report

Firebase Realtime Database is the backend service that is provided by Google for handling backend tasks for your Android apps, IOS apps as well as websites. It provides so many services such as storage, database, and many more. The feature for which Firebase is famous is its Firebase Realtime Database. By using Firebase Realtime Database in your app you can give live data updates to your users without actually refreshing your app. So in this article, we will be creating a simple app in which we will be using Firebase Realtime Database and retrieve the data from the Firebase Realtime database and will see the real-time data changes in our android application using Jetpack Compose. A sample video is given below to get an idea about what we are going to do in this article.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

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 whether 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 platform('com.google.firebase:firebase-bom:30.3.2')
 implementation 'com.google.firebase:firebase-database-ktx'

If the above dependency is not added to your dependencies section. Add this dependency and sync your project. 

Step 3: Add internet permission to 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 4: Working with the MainActivity.kt file

Go to the MainActivity.kt 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.

Kotlin




package com.example.firebaseproject
 
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.firebaseproject.ui.theme.FirebaseProjectTheme
import com.example.firebaseproject.ui.theme.greenColor
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
 
 
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            FirebaseProjectTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    // on below line we are specifying modifier and color for our app
                    modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background
                ) {
                    // on the below line we are specifying the theme as the scaffold.
                    Scaffold(
                        // in scaffold we are specifying the top bar.
                        topBar = {
                            // inside top bar we are specifying background color.
                            TopAppBar(backgroundColor = greenColor,
                                // along with that we are specifying title for our top bar.
                                title = {
                                    // in the top bar we are specifying tile as a text
                                    Text(
                                        // on below line we are specifying
                                        // text to display in top app bar
                                        text = "GFG",
                                        // on below line we are specifying
                                        // modifier to fill max width
                                        modifier = Modifier.fillMaxWidth(),
                                        // on below line we are specifying text alignment
                                        textAlign = TextAlign.Center,
                                        // on below line we are specifying
                                        // color for our text.
                                        color = Color.White
                                    )
                                })
                        }) {
                        firebaseUI(LocalContext.current)
                        // on below line we are calling method to display UI
                    }
                }
            }
        }
    }
}
 
@Composable
fun firebaseUI(context: Context) {
 
    // on below line creating variable for message.
    val message = remember {
        mutableStateOf("")
    }
    // on below line creating variable for firebase
    // database and database reference.
    val firebaseDatabase = FirebaseDatabase.getInstance();
    val databaseReference = firebaseDatabase.getReference("Data");
 
    // on below line adding value event listener for database reference.
    databaseReference.addValueEventListener(object : ValueEventListener {
        override fun onDataChange(snapshot: DataSnapshot) {
            // this method is call to get the realtime
            // updates in the data.
            // this method is called when the data is
            // changed in our Firebase console.
            // below line is for getting the data from
            // snapshot of our database.
            val value = snapshot.getValue(String::class.java)
 
            // after getting the value we are setting
            // our value to message.
            message.value = value!!
        }
 
        override fun onCancelled(error: DatabaseError) {
            // calling on cancelled method when we receive
            // any error or we are not able to get the data.
            Toast.makeText(context, "Fail to get data.", Toast.LENGTH_SHORT).show()
        }
    })
 
    // on below line creating a column
    // to display our retrieved text.
    Column(
        // adding modifier for our column
        modifier = Modifier
            .fillMaxHeight()
            .fillMaxWidth()
            .background(Color.White),
        // on below line adding vertical and
        // horizontal alignment for column.
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // on below line adding a text
        // for displaying heading.
        Text(
            textAlign = TextAlign.Center,
            // on below line adding a text message.
            text = "Retrieve Data from Firebase Realtime Database in Android",
            // on below line we are setting text color
            color = greenColor,
 
            // on below line we are specifying font weight
            fontWeight = FontWeight.Bold,
 
            // on below line we are specifying font family.
            fontFamily = FontFamily.Default,
 
            // on below line we are specifying
            // font size and padding from all sides.
            fontSize = 18.sp, modifier = Modifier.padding(5.dp)
        )
        // on below line adding a spacer.
        Spacer(modifier = Modifier.height(20.dp))
        // on below line adding a text
        // to display retrieved message.
        Text(
            // on below line setting text
            // message from message variable.
            text = message.value,
            fontSize = 20.sp,
            fontStyle = FontStyle.Normal,
            fontWeight = FontWeight.Bold,
            textAlign = TextAlign.Center
        )
    }
}


After adding this code to your app. Now go to Firebase and click on Go to console option which is in 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 a 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 5: Adding data in Firebase Console

Inside Firebase in the Data tab, you are getting to see the below screen. Hover your cursor on null and click on the “+” option on the right side and click on that option. After clicking on that option. Add the data as added in the below image. Make sure to add “Data” in the Name field because we are setting our reference for Firebase as “Data” in our code on line 55. So we have to set it to “Data”. You can change your reference and also change it in the Database. Inside the value field, you can add any data you want. This will be the string that we are going to display inside our text view. After adding data click on the add button and your data will be added in Firebase and this data will be displayed in your app. 

 

After adding this data you will get to see the below screen:  

 

After adding this data run your app and see the output of the app:

Output:

While testing your app you can change your value field in your Firebase console and you can get to see that it will also get updated in your app as well. So in this task, we do not have to refresh our app at any time. As soon as we update the value in our Firebase it will get updated in our App as well. In the below video, we have changed the data from Firebase and it is being updated in-app as well. 



Last Updated : 23 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads