Open In App

Android Jetpack Compose – Read Data From Firebase Firestore

Last Updated : 10 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In the previous article, we have seen How to add data to Firebase Firestore from our android application using Jetpack Compose. In this article, we will take a look at How to read this data from Firebase Firestore in our android application using Jetpack compose. We will be working on the previous application and adding functionality so that we can read the data which is added to our database. 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 Cloud Firestore. Click on that option and you will get to see two options Connect the app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen.  

 

After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to app > Gradle Scripts inside that file. Check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section.

implementation 'com.google.firebase:firebase-firestore:22.0.1'

After adding this dependency sync your project and now we are ready for creating our app. if you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App.  

Step 3: Working with the AndroidManifest.xml file

For adding data to Firebase we should have to give permissions for accessing the internet. for adding these permissions. navigate to app>AndroidManifest.xml. Inside that file add the below permissions to it.  

XML




<!--Permissions for internet-->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


Step 4: Creating a modal class for the Course

Navigate to app>java>your app’s package name>Right click on it>New Kotlin class/file and name it as Course and add the below code to it. Comments are added to it to get to know it in detail. 

Kotlin




package com.example.firebaseproject
 
import java.time.Duration
 
// on below line creating
// a data class for course,
data class Course(
    // on below line creating variables.
    var courseName: String? = "",
    var courseDuration: String? = "",
    var courseDescription: String? = ""
)


Step 5: Create a new activity for reading the courses in our application

Navigate to app>java>your app’s package name> Right-click on it>New>Empty Compose Activity and name it as CourseDetailsActivity. After creating this activity add the below code to it. Comments are added in the code to get to know it in detail. 

Kotlin




package com.example.firebaseproject
 
import android.annotation.SuppressLint
import android.os.Bundle
import android.widget.Toast
import android.content.Context
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.snapshots.SnapshotStateList
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.TextStyle
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.firestore.FirebaseFirestore
 
class CourseDetailsActivity : ComponentActivity() {
   
    @SuppressLint("UnrememberedMutableState")
    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
                                    )
                                })
                        }) {
 
                        // on below line creating variable for list of data.
                        var courseList = mutableStateListOf<Course?>()
                        // on below line creating variable for freebase database
                        // and database reference.
                        var db: FirebaseFirestore = FirebaseFirestore.getInstance()
 
                        // on below line getting data from our database
                        db.collection("Courses").get()
                            .addOnSuccessListener { queryDocumentSnapshots ->
                                // after getting the data we are calling
                                // on success method
                                // and inside this method we are checking
                                // if the received query snapshot is empty or not.
                                if (!queryDocumentSnapshots.isEmpty) {
                                    // if the snapshot is not empty we are
                                    // hiding our progress bar and adding
                                    // our data in a list.
                                    // loadingPB.setVisibility(View.GONE)
                                    val list = queryDocumentSnapshots.documents
                                    for (d in list) {
                                        // after getting this list we are passing that
                                        // list to our object class.
                                        val c: Course? = d.toObject(Course::class.java)
                                        // and we will pass this object class inside
                                        // our arraylist which we have created for list view.
                                        courseList.add(c)
 
                                    }
                                } else {
                                    // if the snapshot is empty we are displaying
                                    // a toast message.
                                    Toast.makeText(
                                        this@CourseDetailsActivity,
                                        "No data found in Database",
                                        Toast.LENGTH_SHORT
                                    ).show()
                                }
                            }
                            // if we don't get any data or any error
                            // we are displaying a toast message
                            // that we donot get any data
                            .addOnFailureListener {
                                Toast.makeText(
                                    this@CourseDetailsActivity,
                                    "Fail to get the data.",
                                    Toast.LENGTH_SHORT
                                ).show()
                            }
                        // on below line we are calling method to display UI
                        firebaseUI(LocalContext.current, courseList)
                    }
                }
            }
        }
    }
 
 
    @OptIn(ExperimentalMaterialApi::class)
    @Composable
    fun firebaseUI(context: Context, courseList: SnapshotStateList<Course?>) {
 
        // on below line creating a column
        // to display our retrieved list.
        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.Top,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // on below line we are
            // calling lazy column
            // for displaying listview.
            LazyColumn {
                // on below line we are setting data
                // for each item of our listview.
                itemsIndexed(courseList) { index, item ->
                    // on below line we are creating
                    // a card for our list view item.
                    Card(
                        onClick = {
                            // inside on click we are
                            // displaying the toast message.
                            Toast.makeText(
                                context,
                                courseList[index]?.courseName + " selected..",
                                Toast.LENGTH_SHORT
                            ).show()
                        },
                        // on below line we are adding
                        // padding from our all sides.
                        modifier = Modifier.padding(8.dp),
 
                        // on below line we are adding
                        // elevation for the card.
                        elevation = 6.dp
                    ) {
                        // on below line we are creating
                        // a row for our list view item.
                        Column(
                            // for our row we are adding modifier
                            // to set padding from all sides.
                            modifier = Modifier
                                .padding(8.dp)
                                .fillMaxWidth()
                        ) {
                            // on below line inside row we are adding spacer
                            Spacer(modifier = Modifier.width(5.dp))
                            // on below line we are displaying course name.
                            courseList[index]?.courseName?.let {
                                Text(
                                    // inside the text on below line we are
                                    // setting text as the language name
                                    // from our modal class.
                                    text = it,
 
                                    // on below line we are adding padding
                                    // for our text from all sides.
                                    modifier = Modifier.padding(4.dp),
 
                                    // on below line we are adding
                                    // color for our text
                                    color = greenColor,
                                    textAlign = TextAlign.Center,
                                    style = TextStyle(
                                        fontSize = 20.sp, fontWeight = FontWeight.Bold
                                    )
                                )
                            }
                            // adding spacer on below line.
                            Spacer(modifier = Modifier.height(5.dp))
 
                            // on below line displaying text for course duration
                            courseList[index]?.courseDuration?.let {
                                Text(
                                    // inside the text on below line we are
                                    // setting text as the language name
                                    // from our modal class.
                                    text = it,
 
                                    // on below line we are adding padding
                                    // for our text from all sides.
                                    modifier = Modifier.padding(4.dp),
 
                                    // on below line we are
                                    // adding color for our text
                                    color = Color.Black,
                                    textAlign = TextAlign.Center,
                                    style = TextStyle(
                                        fontSize = 15.sp
                                    )
                                )
                            }
                            // adding spacer on below line.
                            Spacer(modifier = Modifier.width(5.dp))
                             
                            // on below line displaying text for course description
                            courseList[index]?.courseDescription?.let {
                                Text(
                                    // inside the text on below line we are
                                    // setting text as the language name
                                    // from our modal class.
                                    text = it,
 
                                    // on below line we are adding padding
                                    // for our text from all sides.
                                    modifier = Modifier.padding(4.dp),
 
                                    // on below line we are adding color for our text
                                    color = Color.Black,
                                    textAlign = TextAlign.Center,
                                    style = TextStyle(fontSize = 15.sp)
                                )
                            }
                        }
                    }
                }
 
            }
        }
    }
}


Step 6: 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.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




package com.example.firebaseproject
 
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
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.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat.startActivity
import com.example.firebaseproject.ui.theme.FirebaseProjectTheme
import com.example.firebaseproject.ui.theme.greenColor
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.FirebaseFirestore
 
class MainActivity : ComponentActivity() {
   
    @SuppressLint("UnrememberedMutableState")
    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
                                    )
                                })
                        }) {
                        // on below line we are calling
                        // method to display UI
                        firebaseUI(LocalContext.current)
                    }
                }
            }
        }
    }
}
 
@Composable
fun firebaseUI(context: Context) {
 
    // on below line creating variable for course name,
    // course duration and course description.
    val courseName = remember {
        mutableStateOf("")
    }
 
    val courseDuration = remember {
        mutableStateOf("")
    }
 
    val courseDescription = remember {
        mutableStateOf("")
    }
 
    // on below line creating a column
    // to display our retrieved image view.
    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
    ) {
 
 
        TextField(
            // on below line we are specifying
            // value for our course name text field.
            value = courseName.value,
 
            // on below line we are adding on
            // value change for text field.
            onValueChange = { courseName.value = it },
 
            // on below line we are adding place holder
            // as text as "Enter your course name"
            placeholder = { Text(text = "Enter your course name") },
 
            // on below line we are adding modifier to it
            // and adding padding to it and filling max width
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth(),
 
            // on below line we are adding text style
            // specifying color and font size to it.
            textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),
 
            // on below line we are adding
            // single line to it.
            singleLine = true,
        )
 
        Spacer(modifier = Modifier.height(10.dp))
 
        TextField(
            // on below line we are specifying
            // value for our course duration text field.
            value = courseDuration.value,
 
            // on below line we are adding on
            // value change for text field.
            onValueChange = { courseDuration.value = it },
 
            // on below line we are adding place holder
            // as text as "Enter your course duration"
            placeholder = { Text(text = "Enter your course duration") },
 
            // on below line we are adding modifier to it
            // and adding padding to it and filling max width
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth(),
 
            // on below line we are adding text style
            // specifying color and font size to it.
            textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),
 
            // on below line we are adding
            // single line to it.
            singleLine = true,
        )
 
        Spacer(modifier = Modifier.height(10.dp))
 
        TextField(
            // on below line we are specifying
            // value for our course description text field.
            value = courseDescription.value,
 
            // on below line we are adding on
            // value change for text field.
            onValueChange = { courseDescription.value = it },
 
            // on below line we are adding place holder
            // as text as "Enter your course description"
            placeholder = { Text(text = "Enter your course description") },
 
            // on below line we are adding modifier to it
            // and adding padding to it and filling max width
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth(),
 
            // on below line we are adding text style
            // specifying color and font size to it.
            textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),
 
            // on below line we are adding
            // single line to it.
            singleLine = true,
        )
 
        Spacer(modifier = Modifier.height(10.dp))
 
        // on below line creating button to add data
        // to firebase firestore database.
        Button(
            onClick = {
                // on below line we are validating user input parameters.
                if (TextUtils.isEmpty(courseName.value.toString())) {
                    Toast.makeText(context, "Please enter course name", Toast.LENGTH_SHORT).show()
                } else if (TextUtils.isEmpty(courseDuration.value.toString())) {
                    Toast.makeText(context, "Please enter course Duration", Toast.LENGTH_SHORT)
                        .show()
                } else if (TextUtils.isEmpty(courseDescription.value.toString())) {
                    Toast.makeText(context, "Please enter course description", Toast.LENGTH_SHORT)
                        .show()
                } else {
                    // on below line adding data to firebase firestore database.
                    addDataToFirebase(
                        courseName.value, courseDuration.value, courseDescription.value, context
                    )
                }
            },
            // on below line we are
            // adding modifier to our button.
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            // on below line we are adding text for our button
            Text(text = "Add Data", modifier = Modifier.padding(8.dp))
        }
 
        Spacer(modifier = Modifier.height(10.dp))
 
        Button(
            onClick = {
                // on below line opening course details activity.
                context.startActivity(Intent(context, CourseDetailsActivity::class.java))
            },
            // on below line we are
            // adding modifier to our button.
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            // on below line we are adding text for our button
            Text(text = "View Courses", modifier = Modifier.padding(8.dp))
        }
 
 
    }
}
 
fun addDataToFirebase(
    courseName: String, courseDuration: String, courseDescription: String, context: Context
) {
    // on below line creating an instance of firebase firestore.
    val db: FirebaseFirestore = FirebaseFirestore.getInstance()
     
    // creating a collection reference for our Firebase Firestore database.
    val dbCourses: CollectionReference = db.collection("Courses")
     
    // adding our data to our courses object class.
    val courses = Course(courseName, courseDescription, courseDuration)
 
    // below method is use to add data to Firebase Firestore
    // after the data addition is successful
    dbCourses.add(courses).addOnSuccessListener {
        // we are displaying a success toast message.
        Toast.makeText(
            context, "Your Course has been added to Firebase Firestore", Toast.LENGTH_SHORT
        ).show()
 
    }.addOnFailureListener { e ->
        // this method is called when the data addition process is failed.
        // displaying a toast message when data addition is failed.
        Toast.makeText(context, "Fail to add course \n$e", Toast.LENGTH_SHORT).show()
    }
 
}


After adding this code go to this link to open Firebase. After clicking on this link you will get to see the below page and on this page Click on Go to Console option 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 Firebase Firestore Database in the left window.  

 

After clicking on Create Database option you will get to see the below screen.

 

Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting test mode click on the Next option and you will get to see the below screen.

 

Inside this screen, we just have to click on Enable button to enable our Firebase Firestore database. After completing this process we just have to run our application and add data inside our app and click on submit button. You will get to see the data added inside the Firebase Console.

 

Now run your application to see the output of it. 

Output:



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

Similar Reads