Open In App

Android Jetpack Compose – Add Data to Firebase Firestore

Improve
Improve
Like Article
Like
Save
Share
Report

Firebase is a famous backend service provider of Google which is used to create and manage databases that are required while creating an android application. In this article, we will take a look at How to use the Firebase Firestore database for adding our data to it. 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: 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.os.Bundle
import android.text.TextUtils
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.TextStyle
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.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 descritpion", 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))
        }
    }
}
 
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.
    dbCourses.add(courses).addOnSuccessListener {
       // after the data addition is successful
       // 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. 

 

Below is the output of the app.

Output:



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