Open In App

Android Jetpack Compose – GridView using Firebase Firestore

Improve
Improve
Like Article
Like
Save
Share
Report

GridView is also one of the most used UI components which is used to display items in the Grid format inside our app. By using this type of view we can display the items in the grid format. We have seen this type of GridView in most of the apps. We have also seen the implementation of GridView in our app. In this article, we will take a look at the implementation of GridView using Firebase Firestore in Android using Jetpack Compose.

What we are going to build in this article?

We will be building a simple application in which we will be displaying the data in the grid format and we will load this data from Firebase Firestore inside our GridView using Jetpack Compose. A sample video is given below to get an idea about what we are going to do in this article. Now we will move toward the implementation of this project.

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: Creating a modal class

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

Kotlin




package com.example.firebaseproject
  
data class GridModal(
    // on below line we are creating two variable
    // one is for language name which is string.
    val name: String = "",
  
    // next variable is for our
    // image url which is an string.
    val imageUrl: String = ""
)


Step 3: Adding a new color in the Color.kt file

Navigate to app > java > your app’s package name > ui.theme > Color.kt file and add the below code to it. 

Kotlin




package com.example.newcanaryproject.ui.theme
  
import androidx.compose.ui.graphics.Color
  
val Purple200 = Color(0xFF0F9D58)
val Purple500 = Color(0xFF0F9D58)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
  
// on below line we are adding different colors.
val greenColor = Color(0xFF0F9D58)


Step 4: 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 to 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 5: Working with AndroidManifest.xml

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 6: Working with MainActivity.kt file

Navigate to app>java>your app’s package name>MainActivity.kt file and add the below code to it. Comments are added in the code to get to know in detail.

Kotlin




package com.example.firebaseproject
  
import android.annotation.SuppressLint
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.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.GridCells
import androidx.compose.foundation.lazy.LazyVerticalGrid
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.semantics.Role.Companion.Image
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import coil.compose.rememberAsyncImagePainter
import com.example.firebaseproject.ui.theme.FirebaseProjectTheme
import com.example.firebaseproject.ui.theme.greenColor
import com.google.firebase.auth.*
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.FirebaseFirestore
  
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 
                                    // title 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
                        gridView(LocalContext.current)
                    }
                }
            }
        }
    }
}
  
// on below line we are creating grid view
// function for loading our grid view.
@SuppressLint("UnrememberedMutableState")
@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterialApi::class)
@Composable
fun gridView(context: Context) {
    // on below line we are creating and initializing our array list
    var courseList = mutableStateListOf<GridModal?>()
  
    // on below line creating firebase firestore db 
    val db: FirebaseFirestore = FirebaseFirestore.getInstance()
  
    db.collection("Data").get().addOnSuccessListener {
        // after getting the data we are calling on success method
        // and inside this method we are checking if the recieved
        // query snapshot is empty or not.
        if (!it.isEmpty()) {
            // if the snapshot is not empty
            // we are hiding our progress bar
            // and adding our data in a list.
            val list: List<DocumentSnapshot> = it.getDocuments()
            for (d in list) {
                // after getting this list we are passing 
                // that list to our object class.
                val dataModal: GridModal? = d.toObject(GridModal::class.java)
                // after getting data from Firebase we are storing
                // that data in our array list
                if (dataModal != null) {
                    courseList.add(GridModal(name = dataModal.name, imageUrl = dataModal.imageUrl))
                }
            }
        } else {
            // if the snapshot is empty we are displaying a toast message.
            Toast.makeText(context, "No data found in Database", Toast.LENGTH_SHORT)
                .show()
        }
    }
      
    // on below line we are adding lazy
    // vertical grid for creating a grid view.
    LazyVerticalGrid(
        // on below line we are setting the
        // column count for our grid view.
        cells = GridCells.Fixed(2),
        // on below line we are adding padding
        // from all sides to our grid view.
        modifier = Modifier.padding(10.dp)
    ) {
        // on below line we are displaying our
        // items upto the size of the list.
        items(courseList.size) {
            // on below line we are creating a
            // card for each item of our grid view.
            Card(
                // inside our grid view on below line we are
                // adding on click for each item of our grid view.
                onClick = {
                    // inside on click we are
                    // displaying the toast message.
                    Toast.makeText(
                        context,
                        courseList[it]!!.name + " 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 column on below sides.
                Column(
                    // on below line we are adding padding
                    // padding for our column and filling the max size.
                    Modifier
                        .fillMaxSize()
                        .padding(5.dp),
  
                    // on below line we are adding
                    // horizontal alignment for our column
                    horizontalAlignment = Alignment.CenterHorizontally,
  
                    // on below line we are adding
                    // vertical arrangement for our column
                    verticalArrangement = Arrangement.Center
                ) {
                    // on below line we are creating 
                    // image for our grid view item.
                    Image(
                        // on below line we are adding the image url
                        // from which we will  be loading our image.
                        painter = rememberAsyncImagePainter(courseList[it]!!.imageUrl),
  
                        // on below line we are adding content
                        // description for our image.
                        contentDescription = "gfg image",
  
                        // on below line we are adding modifier for our
                        // image as wrap content for height and width.
                        modifier = Modifier
                            .wrapContentSize()
                            .wrapContentHeight()
                            .wrapContentWidth()
                    )
                    // on the below line we are adding a spacer.
                    Spacer(modifier = Modifier.height(9.dp))
  
                    // on below line we are creating
                    // a text for our grid view item
                    Text(
                        // inside the text on below line we are
                        // setting text as the language name
                        // from our modal class.
                        text = courseList[it]!!.name,
  
                        // 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
                    )
                }
            }
        }
    }
}


Step 7: Adding the data to Firebase Firestore in Android

Search for Firebase in your browser and go to that website and you will get to see the below screen.  

 

After clicking on the Go to Console option. Click on your project which is shown below.

 

After clicking on your project you will get to see the below screen. After clicking on this project you will get to see the below screen.  

 

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 have to add the data inside our Firebase Console. For adding data to our Firebase Console. You have to click on Start Collection Option and give the collection name as Data. After creating a collection you have to click on the Auto option for creating the first document. Inside this create two fields as name and imgUrl and add values inside that fields. Add multiple documents in a similar way inside your Firebase Console. After that run your app and see the output of the app. After adding this data to Firebase run your app and see the output of the app.

Output:



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