Open In App

Android Jetpack Compose – Update Data in Firebase Firestore

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

In the previous article, we have seen How to Add Data to Firebase Firestore in Android, How to read the data from Firebase Firestore in Android. Now we will see How to Update this added data inside our Firebase Firestore. Now we will move towards the implementation of this updating data in Android Firebase using Jetpack Compose. We will be creating a similar screen as we were creating for adding the data and inside this screen, we will be updating our data inside our Firebase Firestore and that data will also be updated inside our app. Below is the video in which we can get to see what we are going to build in this app. A sample video is given below to get an idea about what we are going to do in this article.

Step by Step Implementation

As we have implemented Read and write operation in the previous article which is given below :

  1. Android Jetpack Compose -Adding data to Firebase Firestore.
  2. Android Jetpack Compose – Reading data from Firebase Firestore

Check out the project link for part 1 and part 2. Now we will move towards updating the data inside our Firebase Database in Android. For updating the data we will create a new Activity we will use to update the data.

Step 1: Updating modal class

Navigate to app>java>your app’s package name>Course and 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 com.google.firebase.firestore.Exclude
import java.time.Duration
 
// on below line creating
// a data class for course,
data class Course(
    // on below line creating variables.
    @Exclude var courseID: String? = "",
    var courseName: String? = "",
    var courseDuration: String? = "",
    var courseDescription: String? = ""
)


Step 2: Create a new Compose Activity for updating the data

For creating a new Activity. Navigate to app>res>layout>Right Click on it and click on New>then click on Empty Compose Activity to create a new Activity we will name it as UpdateCourse and 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.content.Context
import android.content.Intent
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.*
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.android.gms.tasks.OnFailureListener
import com.google.android.gms.tasks.OnSuccessListener
import com.google.firebase.firestore.FirebaseFirestore
 
class UpdateCourse : 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 getting data from our database
                        // on below line we are calling method to display UI
                        firebaseUI(
                            LocalContext.current,
                            intent.getStringExtra("courseName"),
                            intent.getStringExtra("courseDuration"),
                            intent.getStringExtra("courseDescription"),
                            intent.getStringExtra("courseID")
                        )
                    }
                }
            }
        }
    }
 
    @Composable
    fun firebaseUI(
        context: Context,
        name: String?,
        duration: String?,
        description: String?,
        courseID: String?
    ) {
 
        // on below line creating variable for course name,
        // course duration and course description.
        val courseName = remember {
            mutableStateOf(name)
        }
 
        val courseDuration = remember {
            mutableStateOf(duration)
        }
 
        val courseDescription = remember {
            mutableStateOf(description)
        }
 
        // on below line creating a column
        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.toString(),
 
                // 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.toString(),
 
                // 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.toString(),
 
                // 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.
                        updateDataToFirebase(
                            courseID,
                            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 = "Update Data", modifier = Modifier.padding(8.dp))
            }
 
            Spacer(modifier = Modifier.height(10.dp))
        }
    }
 
    private fun updateDataToFirebase(
        courseID: String?,
        name: String?,
        duration: String?,
        description: String?,
        context: Context
    ) {
        // inside this method we are passing our updated values
        // inside our object class and later on we
        // will pass our whole object tofirebase Firestore.
        val updatedCourse = Course(courseID, name, duration, description)
 
        // getting our instance from Firebase Firestore.
        val db = FirebaseFirestore.getInstance();
        db.collection("Courses").document(courseID.toString()).set(updatedCourse)
            .addOnSuccessListener {
                // on below line displaying toast message and opening
                // new activity to view courses.
                Toast.makeText(context, "Course Updated successfully..", Toast.LENGTH_SHORT).show()
                context.startActivity(Intent(context, CourseDetailsActivity::class.java))
                finish()
 
            }.addOnFailureListener {
                Toast.makeText(context, "Fail to update course : " + it.message, Toast.LENGTH_SHORT)
                    .show()
            }
    }
}


Step 3: Adding a click listener for items in the list view

Navigate to app>java>your app’s package name>CourseDetailsActivity and 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.content.Intent
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)
                                        c?.courseID = d.id
                                        Log.e("TAG", "Course id is : " + c!!.courseID)
                                        // 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 = {
                            // on below line opening new activity and passing data.
                            val i = Intent(context, UpdateCourse::class.java)
                            i.putExtra("courseName", item?.courseName)
                            i.putExtra("courseDuration", item?.courseDuration)
                            i.putExtra("courseDescription", item?.courseDescription)
                            i.putExtra("courseID", item?.courseID)
                            // inside on click we are opening
                            // new activity to update course details.
                            context.startActivity(i)
 
                        },
                        // 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)
                                )
                            }
                        }
                    }
                }
 
            }
        }
    }
}


Now run your project to see the output of your application. 

Output:



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

Similar Reads