0% found this document useful (0 votes)
23 views11 pages

Lab 8 Note

The document describes a Firebase CRUD app that allows users to create, read, update, and delete data from the Firebase Realtime Database. It includes steps to set up the Firebase database and connect the Android app. The app contains activities for inserting, reading, updating, and deleting data by accessing specific paths in the database and handling the tasks' success or failure. Classes are created to structure the user data being stored in Firebase. Buttons in the activities link to methods that perform the CRUD operations by setting values and getting data from the database.

Uploaded by

Iffah Anisah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views11 pages

Lab 8 Note

The document describes a Firebase CRUD app that allows users to create, read, update, and delete data from the Firebase Realtime Database. It includes steps to set up the Firebase database and connect the Android app. The app contains activities for inserting, reading, updating, and deleting data by accessing specific paths in the database and handling the tasks' success or failure. Classes are created to structure the user data being stored in Firebase. Buttons in the activities link to methods that perform the CRUD operations by setting values and getting data from the database.

Uploaded by

Iffah Anisah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Prepared by Low Han Cheng

Lab 8: Firebase CRUD app


• Firebase Realtime Database (Create, Read, Update, Delete data)

[FrontEnd]

etFirstName etUserName

etLastName
btnRead
etAge
tvFirstName
etUserName
tvLastName

tvAge

btnInsert

[activity_insert_data.xml] [activity_read_data.xml]
btnCreateData

btnReadData

btnUpdateDat
a

btnDeleteData

[activity_main.xml]

etUserName etUserName

etFirstName
btnDelete
etLastName

etAge

btnUpdate

[activity_update_data.xml] [activity_delete_data.xml]
Prepared by Low Han Cheng

[Set Up Firebase Realtime Database]

Create Firebase Realtime Database

Step 1: Log in Google account, go to Firebase Console by browser

Step 2: Open the Firebase > Realtime Database (inside Build) >
Create Database > Set up location > Enable ‘Start in locked mode’

Step 3: Click inside Realtime Database > Rules > Edit rules, change
read & write to ‘true’ > Publish:

Connect to Firebase in Android Studio

Step 1: Tools> Firebase

Step 2: Realtime Database > Get started with Realtime Database


[KOTLIN]

Step 3: Connect to Firebase > Add the Realtime Database SDK to your
app

Access Firebase Authentication system in coding

Step 1: Make variable for Database (before OnCreate function)


private lateinit var database : DatabaseReference
Prepared by Low Han Cheng

[BackEnd]
Activity: MainActivity.kt

*Button functions which link to corresponding activity by using intent


Prepared by Low Han Cheng

Activity: InsertData.kt

Step 1: Button & inputs:


a) Add button function
binding.btnInsert.setOnClickListener{}

b) Set up variables to store input data


val firstName = binding.etFirstName.text.toString()
val lastName = binding.etLastName.text.toString()
val age = binding.etAge.text.toString()
val userName = binding.etUserName.text.toString()

c) Create class file named as ‘User’, which contains the following properties:
data class User(
val firstName : String? = null,
val lastName : String? = null,
val age : String? = null,
val userName : String? = null){
}

d) Define ‘User’ variable which stored the inputs data that passed to the User data class
val User = User(firstName,lastName,age,userName)

Step 2: Insert data into Firebase database: Access this database path
a) Get instance of database and define the location
database = FirebaseDatabase.getInstance().getReference("Users")

b) Insert data and define actions for success or fail task execution

Child path named with the Insert User class data (firstName, lastName, age, username)
username filled by user

database.child(userName).setValue(User).addOnSuccessListener {

binding.etFirstName.text.clear()
binding.etLastName.text.clear() If task
binding.etAge.text.clear()
execution
binding.etUserName.text.clear()
success
Toast.makeText(this,"Successfully Saved", Toast.LENGTH_SHORT).show()

}.addOnFailureListener{ If task
Toast.makeText(this,"Failed", Toast.LENGTH_SHORT).show() execution
} fail
Prepared by Low Han Cheng

package com.example.firebasecrud

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.firebasecrud.databinding.ActivityInsertDataBinding
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase

class InsertData : AppCompatActivity() { Database


private lateinit var binding : ActivityInsertDataBinding
Set Up
private lateinit var database : DatabaseReference

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
binding = ActivityInsertDataBinding.inflate(layoutInflater)
setContentView(binding.root)

binding.btnInsert.setOnClickListener { Step 1
val firstName = binding.etFirstName.text.toString()
val lastName = binding.etLastName.text.toString()
val age = binding.etAge.text.toString()
val userName = binding.etUserName.text.toString()

val User = User(firstName,lastName,age,userName)

database = FirebaseDatabase.getInstance().getReference("Users")
database.child(userName).setValue(User).addOnSuccessListener {

binding.etFirstName.text.clear() Step 2
binding.etLastName.text.clear()
binding.etAge.text.clear()
binding.etUserName.text.clear()

Toast.makeText(this,"Successfully Saved",
Toast.LENGTH_SHORT).show()

}.addOnFailureListener{
Toast.makeText(this,"Failed", Toast.LENGTH_SHORT).show()
}

}
}
}
Prepared by Low Han Cheng

Activity: ReadData.kt

Step 1: Button & inputs:


a) Add button function
binding.btnRead.setOnClickListener{}

b) Set up variables to store username input data


val userName : String = binding.etUsername.text.toString()

c) Validate the input


if (userName.isNotEmpty()){
readData(userName)

}else{

Toast.makeText(this,"PLease enter the Username",


Toast.LENGTH_SHORT).show()

Step 2: Read data in Firebase database:


a) Make function for reading data
private fun readData(userName: String) {}

b) Read data and define actions for success or fail task execution
database = FirebaseDatabase.getInstance().getReference("Users")
database.child(userName).get().addOnSuccessListener {

if (it.exists()){ Read data

val firstname = it.child("firstName").value Read data from


val lastName = it.child("lastName").value
following paths
val age = it.child("age").value If task
Toast.makeText(this,"Successfuly
Read",Toast.LENGTH_SHORT).show() execution
binding.etUsername.text.clear() success
binding.tvFirstName.text = firstname.toString()
binding.tvLastName.text = lastName.toString()
binding.tvAge.text = age.toString()

}
else{
Toast.makeText(this,"User Doesn't
Exist",Toast.LENGTH_SHORT).show()
}
If task
}.addOnFailureListener{ execution
Toast.makeText(this,"Failed",Toast.LENGTH_SHORT).show()
} fail
Prepared by Low Han Cheng

package com.example.firebasecrud

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.firebasecrud.databinding.ActivityInsertDataBinding
import com.example.firebasecrud.databinding.ActivityReadDataBinding
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase

class ReadData : AppCompatActivity() { Database


private lateinit var binding : ActivityReadDataBinding
private lateinit var database : DatabaseReference Set Up

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
binding = ActivityReadDataBinding.inflate(layoutInflater)
setContentView(binding.root)

binding.btnRead.setOnClickListener {
Step 1
val userName : String = binding.etUsername.text.toString()
if (userName.isNotEmpty()){
readData(userName)

}else{

Toast.makeText(this,"PLease enter the Username",


Toast.LENGTH_SHORT).show()

}
}
}

private fun readData(userName: String) {

database = FirebaseDatabase.getInstance().getReference("Users")
database.child(userName).get().addOnSuccessListener { Step 2
if (it.exists()){

val firstname = it.child("firstName").value


val lastName = it.child("lastName").value
val age = it.child("age").value
Toast.makeText(this,"Successfuly
Read",Toast.LENGTH_SHORT).show()
binding.etUsername.text.clear()
binding.tvFirstName.text = firstname.toString()
binding.tvLastName.text = lastName.toString()
binding.tvAge.text = age.toString()
}
else{
Toast.makeText(this,"User Doesn't
Exist",Toast.LENGTH_SHORT).show()
}

}.addOnFailureListener{
Toast.makeText(this,"Failed",Toast.LENGTH_SHORT).show()
}
}
}
Prepared by Low Han Cheng

Activity: UpdateData.kt [pt.1]

Step 1: Button & inputs:


a) Add button function
binding.btnUpdate.setOnClickListener{}

b) Set up variables to store input data and pass them to updateData function
val userName = binding.etUserName.text.toString()
val firstName = binding.etFirstName.text.toString()
val lastName = binding.etLastName.text.toString()
val age = binding.etAge.text.toString()

updateData(userName,firstName,lastName,age)

Step 2: Update data in Firebase database:


a) Make function for updating data
private fun updateData(userName: String, firstName: String, lastName:
String, age: String){}

b) ‘user’ variable which uses HashMap to pair up filled-in data with corresponding path
name in database
val user = mapOf<String,String>(
"firstName" to firstName,
"lastName" to lastName,
"age" to age
)

c) Update data and define actions for success or fail task execution
database = FirebaseDatabase.getInstance().getReference("Users")
database.child(userName).updateChildren(user).addOnSuccessListener {

binding.etUserName.text.clear() Update data


binding.etFirstName.text.clear() If task
binding.etLastName.text.clear() execution
binding.etAge.text.clear() success
Toast.makeText(this,"Successfuly Updated",
Toast.LENGTH_SHORT).show()

}.addOnFailureListener{
Toast.makeText(this,"Failed to Update", If task
Toast.LENGTH_SHORT).show() execution
} fail
}
Prepared by Low Han Cheng

package com.example.firebasecrud

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.firebasecrud.databinding.ActivityReadDataBinding
import com.example.firebasecrud.databinding.ActivityUpdateDataBinding
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase

class UpdateData : AppCompatActivity() {


Database
private lateinit var binding : ActivityUpdateDataBinding
private lateinit var database : DatabaseReference Set Up

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
binding = ActivityUpdateDataBinding.inflate(layoutInflater)
setContentView(binding.root)

binding.btnUpdate.setOnClickListener {
Step 1
val userName = binding.etUserName.text.toString()
val firstName = binding.etFirstName.text.toString()
val lastName = binding.etLastName.text.toString()
val age = binding.etAge.text.toString()

updateData(userName,firstName,lastName,age)

}
}

private fun updateData(userName: String, firstName: String, lastName:


String, age: String) {

val user = mapOf<String,String>(


"firstName" to firstName,
"lastName" to lastName,
"age" to age
Step 2
)

database = FirebaseDatabase.getInstance().getReference("Users")
database.child(userName).updateChildren(user).addOnSuccessListener
{

binding.etUserName.text.clear()
binding.etFirstName.text.clear()
binding.etLastName.text.clear()
binding.etAge.text.clear()
Toast.makeText(this,"Successfuly Updated",
Toast.LENGTH_SHORT).show()

}.addOnFailureListener{
Toast.makeText(this,"Failed to Update",
Toast.LENGTH_SHORT).show()
}
}
}
Prepared by Low Han Cheng

Activity: DeleteData.kt

Step 1: Button & inputs:


a) Add button function
binding.btnDeleteData.setOnClickListener{}

b) Set up variables to store username input data


val userName : String = binding.etUsername.text.toString()

c) Validate the input


if(userName.isNotEmpty()){
deleteData(userName)
}
else{
Toast.makeText(this,"Please enter the username",
Toast.LENGTH_SHORT).show()
}

Step 2: Delete data in Firebase database:


a) Make function for deleting data
private fun deleteData(userName: String) {}

b) Delete data and define actions for success or fail task execution
database = FirebaseDatabase.getInstance().getReference("Users")
database.child(userName).removeValue().addOnSuccessListener {
If task
binding.etUsername.text.clear() Delete data execution
Toast.makeText(this,"Deleted Successfully",
Toast.LENGTH_SHORT).show() success

}.addOnFailureListener{
Toast.makeText(this,"Failed to Delete", Toast.LENGTH_SHORT).show() If task
} execution
fail
Prepared by Low Han Cheng

package com.example.firebasecrud

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.firebasecrud.databinding.ActivityDeleteDataBinding
import com.example.firebasecrud.databinding.ActivityUpdateDataBinding
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase

class DeleteData : AppCompatActivity() {


private lateinit var binding : ActivityDeleteDataBinding Database
private lateinit var database : DatabaseReference Set Up
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDeleteDataBinding.inflate(layoutInflater)
setContentView(binding.root)

binding.btnDeleteData.setOnClickListener {
Step 1
val userName = binding.etUsername.text.toString()
if(userName.isNotEmpty()){
deleteData(userName)
}
else{
Toast.makeText(this,"Please enter the username",
Toast.LENGTH_SHORT).show()
}
}
}

private fun deleteData(userName: String) {

database = FirebaseDatabase.getInstance().getReference("Users")
database.child(userName).removeValue().addOnSuccessListener {

binding.etUsername.text.clear()
Toast.makeText(this,"Deleted Successfully", Step 2
Toast.LENGTH_SHORT).show()

}.addOnFailureListener{
Toast.makeText(this,"Failed to Delete",
Toast.LENGTH_SHORT).show()
}
}
}

You might also like