Hey guys, here is the complete Firebase Realtime Database Android with Kotlin guide. Firebase realtime database is NoSQL database which means we don’t have the traditional columns and rows.
In firebase realtime database we can store data in the form of JSON tree structure like below.
In this post we will create an app in which we will perform the CRUD operation of firebase realtime database (Create, Read, Update and Delete).
Firebase Realtime Database Video Tutorial
If you are more comfortable in learning with video tutorials, then here is the tutorial playlist of Firebase Realtime Database Android Kotlin.
Firebase Realtime Database CRUD Operations
First of all create a new android project and then you will need to connect your android with firebase to use firebase realtime database in your android project.
Below is the detailed video tutorial of How to create new Firebase project and how to connect that project with your android project.
After creating and connecting firebase project with android project go to android studio and open activity_main.xml, inside activity_main.xml file paste the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".activities.MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Firebase Realtime Database App in Kotlin" android:layout_marginTop="80dp" android:textSize="28sp" android:gravity="center" android:textStyle="bold" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/btnInsertData" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="insert Data" android:layout_marginTop="75dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" /> <Button android:id="@+id/btnFetchData" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="75dp" android:text="Fetch Data" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/btnInsertData" /> </androidx.constraintlayout.widget.ConstraintLayout> |
Now open MainActivity.kt and paste the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class MainActivity : AppCompatActivity() { private lateinit var btnInsertData: Button private lateinit var btnFetchData: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btnInsertData = findViewById(R.id.btnInsertData) btnFetchData = findViewById(R.id.btnFetchData) btnInsertData.setOnClickListener { val intent = Intent(this, InsertionActivity::class.java) startActivity(intent) } btnFetchData.setOnClickListener { val intent = Intent(this, FetchingActivity::class.java) startActivity(intent) } } } |
After these changes in MainActivity, let’s create 3 more activities.
- InsertionActivity (for inserting employee details)
- FetchingActivity (for fetching employee name only)
- EmployeeDetailsActivity (for showing employee full details)
In EmployeeDetailsActivity we will also add 2 buttons for Updating & Deleting employee record but we will do it later in this post.
InsertionActivity
Open activity_insertion.xml and paste the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".activities.InsertionActivity"> <EditText android:id="@+id/etEmpName" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:ems="10" android:inputType="textPersonName" android:hint="Enter name" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <EditText android:id="@+id/etEmpAge" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:ems="10" android:inputType="textPersonName" android:hint="Enter age" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/etEmpName" /> <EditText android:id="@+id/etEmpSalary" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:ems="10" android:inputType="textPersonName" android:hint="Enter salary" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/etEmpAge" /> <Button android:id="@+id/btnSave" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="32dp" android:text="Save Data" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/etEmpSalary" /> </androidx.constraintlayout.widget.ConstraintLayout> |
Now go to InsertionActivity.kt and paste the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
class InsertionActivity : AppCompatActivity() { private lateinit var etEmpName: EditText private lateinit var etEmpAge: EditText private lateinit var etEmpSalary: EditText private lateinit var btnSaveData: Button private lateinit var dbRef: DatabaseReference override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_insertion) etEmpName = findViewById(R.id.etEmpName) etEmpAge = findViewById(R.id.etEmpAge) etEmpSalary = findViewById(R.id.etEmpSalary) btnSaveData = findViewById(R.id.btnSave) dbRef = FirebaseDatabase.getInstance().getReference("Employees") btnSaveData.setOnClickListener { saveEmployeeData() } } private fun saveEmployeeData() { //getting values val empName = etEmpName.text.toString() val empAge = etEmpAge.text.toString() val empSalary = etEmpSalary.text.toString() if (empName.isEmpty()) { etEmpName.error = "Please enter name" } if (empAge.isEmpty()) { etEmpAge.error = "Please enter age" } if (empSalary.isEmpty()) { etEmpSalary.error = "Please enter salary" } val empId = dbRef.push().key!! val employee = EmployeeModel(empId, empName, empAge, empSalary) dbRef.child(empId).setValue(employee) .addOnCompleteListener { Toast.makeText(this, "Data inserted successfully", Toast.LENGTH_LONG).show() etEmpName.text.clear() etEmpAge.text.clear() etEmpSalary.text.clear() }.addOnFailureListener { err -> Toast.makeText(this, "Error ${err.message}", Toast.LENGTH_LONG).show() } } } |
After these changes run you app and you will be able to store data in firebase realtime database.
FetchingActivity
In order to fetch data from firebase realtime database and show in a recyclerview we need to create a recyclerview item layout, so let’s do it.
Create a new Layout Resource File in res->layout, I will name it emp_list_item you can name it anything you want.
After creating new Layout Resource File paste the following code there.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" xmlns:app="http://schemas.android.com/apk/res-auto" app:cardElevation="8dp" app:cardCornerRadius="8dp" android:layout_margin="8dp"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:padding="16dp" android:layout_gravity="center" android:orientation="vertical"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:orientation="horizontal"> <TextView android:id="@+id/tvEmpName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Emp Name" android:layout_gravity="center" android:gravity="center" android:textColor="@color/black" android:textSize="30sp" android:textStyle="bold"/> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> |
As we will fetch the Employee details from firebase realtime database, so we will need a data class for Employee.
Create new Kotlin data class and name it EmployeeModel and paste the following code there.
1 2 3 4 5 6 |
data class EmployeeModel( var empId: String? = null, var empName: String? = null, var empAge: String? = null, var empSalary: String? = null ) |
To work with RecyclerView in android we need an Adapter class, so create a new Kotlin class and name it EmpAdapter or any name you want.
After creating Adapter class paste the below code there.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
class EmpAdapter(private val empList: ArrayList<EmployeeModel>) : RecyclerView.Adapter<EmpAdapter.ViewHolder>() { private lateinit var mListener: onItemClickListener interface onItemClickListener{ fun onItemClick(position: Int) } fun setOnItemClickListener(clickListener: onItemClickListener){ mListener = clickListener } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val itemView = LayoutInflater.from(parent.context).inflate(R.layout.emp_list_item, parent, false) return ViewHolder(itemView, mListener) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val currentEmp = empList[position] holder.tvEmpName.text = currentEmp.empName } override fun getItemCount(): Int { return empList.size } class ViewHolder(itemView: View, clickListener: onItemClickListener) : RecyclerView.ViewHolder(itemView) { val tvEmpName : TextView = itemView.findViewById(R.id.tvEmpName) init { itemView.setOnClickListener { clickListener.onItemClick(adapterPosition) } } } } |
Now go to activity_fetching.xml and paste the below code there.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".activities.FetchingActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/rvEmp" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginStart="1dp" android:layout_marginTop="1dp" android:layout_marginEnd="1dp" android:layout_marginBottom="1dp" tools:listitem="@layout/emp_list_item" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/tvLoadingData" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Loading Data....." android:textSize="28sp" android:textColor="@color/black" android:textStyle="bold" android:visibility="gone" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> |
So the activity_fetching.xml file is set, now go to FetchingActivity.kt and paste the following code there.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
class FetchingActivity : AppCompatActivity() { private lateinit var empRecyclerView: RecyclerView private lateinit var tvLoadingData: TextView private lateinit var empList: ArrayList<EmployeeModel> private lateinit var dbRef: DatabaseReference override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_fetching) empRecyclerView = findViewById(R.id.rvEmp) empRecyclerView.layoutManager = LinearLayoutManager(this) empRecyclerView.setHasFixedSize(true) tvLoadingData = findViewById(R.id.tvLoadingData) empList = arrayListOf<EmployeeModel>() getEmployeesData() } private fun getEmployeesData() { empRecyclerView.visibility = View.GONE tvLoadingData.visibility = View.VISIBLE dbRef = FirebaseDatabase.getInstance().getReference("Employees") dbRef.addValueEventListener(object : ValueEventListener{ override fun onDataChange(snapshot: DataSnapshot) { empList.clear() if (snapshot.exists()){ for (empSnap in snapshot.children){ val empData = empSnap.getValue(EmployeeModel::class.java) empList.add(empData!!) } val mAdapter = EmpAdapter(empList) empRecyclerView.adapter = mAdapter mAdapter.setOnItemClickListener(object : EmpAdapter.onItemClickListener{ override fun onItemClick(position: Int) { val intent = Intent(this@FetchingActivity, EmployeeDetailsActivity::class.java) //put extras intent.putExtra("empId", empList[position].empId) intent.putExtra("empName", empList[position].empName) intent.putExtra("empAge", empList[position].empAge) intent.putExtra("empSalary", empList[position].empSalary) startActivity(intent) } }) empRecyclerView.visibility = View.VISIBLE tvLoadingData.visibility = View.GONE } } override fun onCancelled(error: DatabaseError) { TODO("Not yet implemented") } }) } } |
EmployeeDetailsActivity
Open activity_employee_details.xml and paste the below code there.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 |
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".activities.EmployeeDetailsActivity"> <Button android:id="@+id/btnUpdate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:text="Update" app:layout_constraintEnd_toStartOf="@+id/btnDelete" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/linearLayout" /> <Button android:id="@+id/btnDelete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:text="Delete" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toEndOf="@+id/btnUpdate" app:layout_constraintTop_toBottomOf="@id/linearLayout" /> <LinearLayout android:id="@+id/linearLayout" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintEnd_toEndOf="parent" android:orientation="vertical"> <LinearLayout android:id="@+id/id_lin" android:layout_width="match_parent" android:layout_height="30dp" android:layout_marginLeft="10dp" android:layout_marginTop="20dp" android:layout_marginRight="10dp" android:orientation="horizontal" android:weightSum="2" > <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="0.6" android:background="@color/divider_grey"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:text="Emp id" android:textColor="@color/black" android:textSize="15sp" /> </LinearLayout> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1.4"> <TextView android:id="@+id/tvEmpId" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:text="" android:textColor="@color/black" android:textSize="15sp" /> </LinearLayout> </LinearLayout> <LinearLayout android:id="@+id/contact_lin" android:layout_width="match_parent" android:layout_height="40dp" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:orientation="horizontal" android:weightSum="2"> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="0.6" android:background="@color/divider_grey"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:text="Emp Name" android:textColor="@color/black" android:textSize="15sp" /> </LinearLayout> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1.4"> <TextView android:id="@+id/tvEmpName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:text="" android:textColor="@color/black" android:textSize="15sp" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="40dp" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:orientation="horizontal" android:weightSum="2" > <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="0.6" android:background="@color/divider_grey"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:text="Emp Age" android:textColor="@color/black" android:textSize="15sp" /> </LinearLayout> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1.4"> <TextView android:id="@+id/tvEmpAge" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:text="" android:textColor="@color/black" android:textSize="15sp" /> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="40dp" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:orientation="horizontal" android:weightSum="2" > <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="0.6" android:background="@color/divider_grey"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:text="Emp Salary" android:textColor="@color/black" android:textSize="15sp" /> </LinearLayout> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1.4"> <TextView android:id="@+id/tvEmpSalary" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:text="" android:textColor="@color/black" android:textSize="15sp" /> </LinearLayout> </LinearLayout> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout> |
As you can see in the above xml file we have 2 buttons (btnUpdate & btnDelete) we will use these buttons for updating and deleting data from firebase realtime database.
But first of all we will initialize all the views and we will set employee data to the views.
We are passing employee data from the FetchingActivity.kt, so paste the below code in EmployeeDetailsActivity.kt.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
private lateinit var tvEmpId: TextView private lateinit var tvEmpName: TextView private lateinit var tvEmpAge: TextView private lateinit var tvEmpSalary: TextView private lateinit var btnUpdate: Button private lateinit var btnDelete: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_employee_details) initView() setValuesToViews() } private fun initView() { tvEmpId = findViewById(R.id.tvEmpId) tvEmpName = findViewById(R.id.tvEmpName) tvEmpAge = findViewById(R.id.tvEmpAge) tvEmpSalary = findViewById(R.id.tvEmpSalary) btnUpdate = findViewById(R.id.btnUpdate) btnDelete = findViewById(R.id.btnDelete) } private fun setValuesToViews() { tvEmpId.text = intent.getStringExtra("empId") tvEmpName.text = intent.getStringExtra("empName") tvEmpAge.text = intent.getStringExtra("empAge") tvEmpSalary.text = intent.getStringExtra("empSalary") } } |
Updating Record
For updating data in database we will show a dialog to the user, so create new resource file in the layout directory and name it update_dialog and paste the below code there.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="10dp"> <EditText android:id="@+id/etEmpName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:hint="Employee Name" android:inputType="textPersonName" /> <EditText android:id="@+id/etEmpAge" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:ems="10" android:hint="Employee Age" /> <EditText android:id="@+id/etEmpSalary" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:ems="10" android:hint="Employee Salary" android:inputType="textPersonName" /> <Button android:id="@+id/btnUpdateData" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="20dp" android:text="Update Data" /> </LinearLayout> |
Now inside onCreate() method of EmployeeDetailsActivity.kt set a click listener on btnUpdate and call openUpdateDialog() method inside the btnUpdate click listener like below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
class EmployeeDetailsActivity : AppCompatActivity() { private lateinit var tvEmpId: TextView private lateinit var tvEmpName: TextView private lateinit var tvEmpAge: TextView private lateinit var tvEmpSalary: TextView private lateinit var btnUpdate: Button private lateinit var btnDelete: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_employee_details) initView() setValuesToViews() btnUpdate.setOnClickListener { openUpdateDialog( intent.getStringExtra("empId").toString(), intent.getStringExtra("empName").toString() ) } } private fun openUpdateDialog( empId: String, empName: String ) { val mDialog = AlertDialog.Builder(this) val inflater = layoutInflater val mDialogView = inflater.inflate(R.layout.update_dialog, null) mDialog.setView(mDialogView) val etEmpName = mDialogView.findViewById<EditText>(R.id.etEmpName) val etEmpAge = mDialogView.findViewById<EditText>(R.id.etEmpAge) val etEmpSalary = mDialogView.findViewById<EditText>(R.id.etEmpSalary) val btnUpdateData = mDialogView.findViewById<Button>(R.id.btnUpdateData) etEmpName.setText(intent.getStringExtra("empName").toString()) etEmpAge.setText(intent.getStringExtra("empAge").toString()) etEmpSalary.setText(intent.getStringExtra("empSalary").toString()) mDialog.setTitle("Updating $empName Record") val alertDialog = mDialog.create() alertDialog.show() btnUpdateData.setOnClickListener { updateEmpData( empId, etEmpName.text.toString(), etEmpAge.text.toString(), etEmpSalary.text.toString() ) Toast.makeText(applicationContext, "Employee Data Updated", Toast.LENGTH_LONG).show() //we are setting updated data to our textviews tvEmpName.text = etEmpName.text.toString() tvEmpAge.text = etEmpAge.text.toString() tvEmpSalary.text = etEmpSalary.text.toString() alertDialog.dismiss() } } private fun updateEmpData( id: String, name: String, age: String, salary: String ) { val dbRef = FirebaseDatabase.getInstance().getReference("Employees").child(id) val empInfo = EmployeeModel(id, name, age, salary) dbRef.setValue(empInfo) } } |
In the above code when user click on btnUpdate the dialog will be displayed and user can then change the data and when user
click the update button in dialog we will update the Employee data by using empId as unique key identifier.
Deleting Record
For deleting the record add a click listener on btnDelete and inside the
click listener call the deleteRecord() method and pass empId as a unique identifier to delete the specific record.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
package com.example.firebasekotlin.activities import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AlertDialog import com.example.firebasekotlin.R import com.example.firebasekotlin.models.EmployeeModel import com.google.firebase.database.FirebaseDatabase class EmployeeDetailsActivity : AppCompatActivity() { private lateinit var tvEmpId: TextView private lateinit var tvEmpName: TextView private lateinit var tvEmpAge: TextView private lateinit var tvEmpSalary: TextView private lateinit var btnUpdate: Button private lateinit var btnDelete: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_employee_details) initView() setValuesToViews() btnUpdate.setOnClickListener { openUpdateDialog( intent.getStringExtra("empId").toString(), intent.getStringExtra("empName").toString() ) } btnDelete.setOnClickListener { deleteRecord( intent.getStringExtra("empId").toString() ) } } private fun initView() { tvEmpId = findViewById(R.id.tvEmpId) tvEmpName = findViewById(R.id.tvEmpName) tvEmpAge = findViewById(R.id.tvEmpAge) tvEmpSalary = findViewById(R.id.tvEmpSalary) btnUpdate = findViewById(R.id.btnUpdate) btnDelete = findViewById(R.id.btnDelete) } private fun setValuesToViews() { tvEmpId.text = intent.getStringExtra("empId") tvEmpName.text = intent.getStringExtra("empName") tvEmpAge.text = intent.getStringExtra("empAge") tvEmpSalary.text = intent.getStringExtra("empSalary") } private fun deleteRecord( id: String ){ val dbRef = FirebaseDatabase.getInstance().getReference("Employees").child(id) val mTask = dbRef.removeValue() mTask.addOnSuccessListener { Toast.makeText(this, "Employee data deleted", Toast.LENGTH_LONG).show() val intent = Intent(this, FetchingActivity::class.java) finish() startActivity(intent) }.addOnFailureListener{ error -> Toast.makeText(this, "Deleting Err ${error.message}", Toast.LENGTH_LONG).show() } } } |
EmployeeDetailsActivity Complete Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 |
class EmployeeDetailsActivity : AppCompatActivity() { private lateinit var tvEmpId: TextView private lateinit var tvEmpName: TextView private lateinit var tvEmpAge: TextView private lateinit var tvEmpSalary: TextView private lateinit var btnUpdate: Button private lateinit var btnDelete: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_employee_details) initView() setValuesToViews() btnUpdate.setOnClickListener { openUpdateDialog( intent.getStringExtra("empId").toString(), intent.getStringExtra("empName").toString() ) } btnDelete.setOnClickListener { deleteRecord( intent.getStringExtra("empId").toString() ) } } private fun initView() { tvEmpId = findViewById(R.id.tvEmpId) tvEmpName = findViewById(R.id.tvEmpName) tvEmpAge = findViewById(R.id.tvEmpAge) tvEmpSalary = findViewById(R.id.tvEmpSalary) btnUpdate = findViewById(R.id.btnUpdate) btnDelete = findViewById(R.id.btnDelete) } private fun setValuesToViews() { tvEmpId.text = intent.getStringExtra("empId") tvEmpName.text = intent.getStringExtra("empName") tvEmpAge.text = intent.getStringExtra("empAge") tvEmpSalary.text = intent.getStringExtra("empSalary") } private fun deleteRecord( id: String ){ val dbRef = FirebaseDatabase.getInstance().getReference("Employees").child(id) val mTask = dbRef.removeValue() mTask.addOnSuccessListener { Toast.makeText(this, "Employee data deleted", Toast.LENGTH_LONG).show() val intent = Intent(this, FetchingActivity::class.java) finish() startActivity(intent) }.addOnFailureListener{ error -> Toast.makeText(this, "Deleting Err ${error.message}", Toast.LENGTH_LONG).show() } } private fun openUpdateDialog( empId: String, empName: String ) { val mDialog = AlertDialog.Builder(this) val inflater = layoutInflater val mDialogView = inflater.inflate(R.layout.update_dialog, null) mDialog.setView(mDialogView) val etEmpName = mDialogView.findViewById<EditText>(R.id.etEmpName) val etEmpAge = mDialogView.findViewById<EditText>(R.id.etEmpAge) val etEmpSalary = mDialogView.findViewById<EditText>(R.id.etEmpSalary) val btnUpdateData = mDialogView.findViewById<Button>(R.id.btnUpdateData) etEmpName.setText(intent.getStringExtra("empName").toString()) etEmpAge.setText(intent.getStringExtra("empAge").toString()) etEmpSalary.setText(intent.getStringExtra("empSalary").toString()) mDialog.setTitle("Updating $empName Record") val alertDialog = mDialog.create() alertDialog.show() btnUpdateData.setOnClickListener { updateEmpData( empId, etEmpName.text.toString(), etEmpAge.text.toString(), etEmpSalary.text.toString() ) Toast.makeText(applicationContext, "Employee Data Updated", Toast.LENGTH_LONG).show() //we are setting updated data to our textviews tvEmpName.text = etEmpName.text.toString() tvEmpAge.text = etEmpAge.text.toString() tvEmpSalary.text = etEmpSalary.text.toString() alertDialog.dismiss() } } private fun updateEmpData( id: String, name: String, age: String, salary: String ) { val dbRef = FirebaseDatabase.getInstance().getReference("Employees").child(id) val empInfo = EmployeeModel(id, name, age, salary) dbRef.setValue(empInfo) } } |
So guys at this point our tutorial is completed and in the above steps we
performed the CRUD operations of Firebase Realtime Database with Kotlin.
Happy Coding…
Hi i used same code. App data not going to store firebase