Open In App

Android Jetpack Compose – Add Data to Firebase Realtime Database

Improve
Improve
Like Article
Like
Save
Share
Report

Firebase Realtime Database provides us with a feature to give Real-time updates to your data inside your app within milliseconds. With the help of Firebase, you can provide Real-time updates to your users. In this article, we will take a look at How to add data to Firebase Realtime Database in Android 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: 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 3: 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 Connect the 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 4: 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 5: Creating a Modal class

Navigate to app>java>your app’s package name>Right click on it>New>Kotlin class and name it as EmployeeObj 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
 
data class EmployeeObj(
    // on below line creating variables
    // for employee name, contact number
    // and address
    var employeeName: String,
    var employeeContactNumber: String,
    var employeeAddress: String
)


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.os.Bundle
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.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
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.*
 
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 creating variable for freebase database
                        // and database reference.
                        val firebaseDatabase = FirebaseDatabase.getInstance();
                        val databaseReference = firebaseDatabase.getReference("EmployeeInfo");
 
                        // on below line we are calling method to display UI
                        firebaseUI(LocalContext.current, databaseReference)
                    }
                }
            }
        }
    }
}
 
@Composable
fun firebaseUI(context: Context, databaseReference: DatabaseReference) {
 
    val name = remember {
        mutableStateOf(TextFieldValue())
    }
 
    val address = remember {
        mutableStateOf(TextFieldValue())
    }
 
    val contactNumber = remember {
        mutableStateOf(TextFieldValue())
    }
 
    // 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
    ) {
 
        Text(
            text = "Add data to Firebase Realtime Database",
            // in modifier we are specifying padding
            // for our text from all sides.
            modifier = Modifier.padding(10.dp),
            // on below line we are specifying
            // style for our text
            style = TextStyle(
                color = Color.Black, fontSize = 20.sp
            ), fontWeight = FontWeight.Bold
        )
 
        // on below line we are creating
        // a text field for our email.
        TextField(
            // on below line we are specifying
            // value for our email text field.
            value = name.value,
 
            // on below line we are adding on
            // value change for text field.
            onValueChange = { name.value = it },
 
            // on below line we are adding place holder
            // as text as "Enter your email"
            placeholder = { Text(text = "Enter your 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,
        )
 
        // on below line we are adding spacer
        Spacer(modifier = Modifier.height(10.dp))
 
        // on below line we are creating
        // a text field for our email.
        TextField(
            // on below line we are specifying
            // value for our email text field.
            value = contactNumber.value,
 
            // on below line we are adding on
            // value change for text field.
            onValueChange = { contactNumber.value = it },
 
            // on below line we are adding place holder
            // as text as "Enter your email"
            placeholder = { Text(text = "Enter your contact number") },
 
            // 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,
        )
 
        // on below line we are adding spacer
        Spacer(modifier = Modifier.height(10.dp))
 
        // on below line we are creating
        // a text field for our email.
        TextField(
            // on below line we are specifying
            // value for our email text field.
            value = address.value,
 
            // on below line we are adding on
            // value change for text field.
            onValueChange = { address.value = it },
 
            // on below line we are adding place holder
            // as text as "Enter your email"
            placeholder = { Text(text = "Enter your address") },
 
            // 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,
        )
 
        // on below line we are adding spacer
        Spacer(modifier = Modifier.height(10.dp))
 
        // on below line creating button
        Button(
            onClick = {
                // on below line we are adding data.
                val empObj =
                    EmployeeObj(name.value.text, contactNumber.value.text, address.value.text);
                // we are use add value event listener method
                // which is called with database reference.
                databaseReference.addValueEventListener(object : ValueEventListener {
                    override fun onDataChange(snapshot: DataSnapshot) {
                        // inside the method of on Data change we are setting
                        // our object class to our database reference.
                        // data base reference will sends data to firebase.
                        databaseReference.setValue(empObj)
 
                        // after adding this data we
                        // are showing toast message.
                        Toast.makeText(
                            context,
                            "Data added to Firebase Database",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
 
                    override fun onCancelled(error: DatabaseError) {
                        // if the data is not added or it is cancelled then
                        // we are displaying a failure toast message.
                        Toast.makeText(
                            context,
                            "Fail to add data $error",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                })
            },
            // 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 Employee Details", modifier = Modifier.padding(8.dp))
        }
    }
}


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.

Now run your project to add new data to Firebase Realtime Database. 

Output

Below is the video for our app for adding data to the Firebase Realtime Database.

Run the app and make sure to connect your device to the internet. After that add some data in your text fields and click on the Insert data button. The data will be added to our Firebase Database. Below is the screenshot we will get to see after adding data to Firebase Database from the app.

 



Last Updated : 26 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads