Firebase: Realtime Database Update and Delete FIREBASE
- Firebase Tutorial
- Features of Firebase
- Android Studio
- Firebase - Environment Setup (with android studio)
- Firebase Assistance - Android Studio
- Firebase Authentication
- Firebase: Google Sign-In Authentication
- Firebase: Facebook Sign-In Authentication
- Firebase: Sign-In Authentication Using Phone Number
- Firebase UI: Authentication using email/password
- Firebase UI: Authentication using email link
- Firebase SDK: Authentication using email/password
- Firebase SDK: Authentication using the email link
- Firebase: Realtime Database
- Firebase: Real-time database setup and configuration
- Firebase: Data Organization in Real-time Database
- Firebase: Realtime Database Reading and Writing
- Firebase: Realtime Database Update and Delete
Firebase: Realtime Database Update and Delete
Firebase: Realtime Database Update and Delete
In our previous section(Firebase: Realtime Database Reading and Writing), we learned how we could read and write data into the database. Now, we will learn how we can modify and delete the data from the database.
Update
For updating a single node in our JSON database, we simply use setValue() on the correct child reference.
- correct child reference.
- myRef.setValue("Hello, World")
- myRef.child("someChild").child("name").setValue(name)
If we want to write to a specific child of a node without overwriting other child nodes, we use the updateChildren() method. When we call updateChildren(), we can update lower-level child values by specifying a path for the key.
For example
- //writeNewPost function for chat application
- private fun Newpost(userId:String, username:String, title:String, body:String){
- //creating new post at /user-posts/$userid/$postid simultaneously
- //Using push key
- val key=database.child("posts").push().key
- //Checking it is null or not
- if(key==null){
- Log.w(TAG,"Could not get push key for posts")
- return
- }
- //Creating Post object
- val post=Post(userId, username, title, body)
- //Push it to a map
- val postValues=post.toMap()
- val childUpdates=HashMap<String,Any>()
- childUpdates["/posts/$key"]=postValues
- childUpdates["/user-posts/$userId/$key"]=postValues
- database.updateChildren(childUpdates)
- }
The push()
method is used to create a post in the node containing post for all user at /posts/$postid and simultaneously retrieves the key with getKey()
method. The key is then used to create a second entry in the user's posts at /user-posts/$userid/$postid
. Using /user-posts/$userid/$postid
path, we can simultaneously update to multiple locations in the JSON tree with a single call to updateChildren()
. Updates are made in a way that they are atomic means either all updates succeed or all updates fail.
Adding a Completion Callback
If you want to know when our data has been committed, you can add a completion listener. Both the setValue()
and updateChildren()
take an optional completion listener. It will be called when the write has been successfully committed to the database. The listener is passed an error object if the call was unsuccessful. This error object indicates why the failure occurred.
- database.child("users").child(userId).setValue(user)
- .addOnSuccessListener{
- //Write was successful!
- //?.
- }
- .addOnFailureListener{
- //Write failed
- //?
- }
Delete
The simplest way for deleting data is to call removeValue()
on a reference to the location of that data. We can also delete data by specifying null as the value for another write operation such as setValue()
or updateChildren()
. We can use this technique with updateChildren()
to delete multiple children in a single API call.
activity_upd_del.xml
upd_del.kt
package com.example.firebaserealtimedatabase
- import androidx.appcompat.app.AppCompatActivity
- import android.os.Bundle
- import android.text.TextUtils
- import android.util.Log
- import android.view.View
- import android.widget.Toast
- import com.google.firebase.auth.FirebaseAuth
- import com.google.firebase.database.*
- import kotlinx.android.synthetic.main.activity_upd_del.*
- import kotlinx.android.synthetic.main.activity_welcome.*
- import kotlinx.android.synthetic.main.activity_welcome.email
- class upd_del : AppCompatActivity() {
- private var mFirebaseDatabase: DatabaseReference? = null
- private var mFirebaseInstance: FirebaseDatabase? = null
- private var userId: String? = null
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_upd_del)
- mFirebaseInstance = FirebaseDatabase.getInstance()
- // get reference to 'users' node
- mFirebaseDatabase = mFirebaseInstance!!.getReference("users")
- val user = FirebaseAuth.getInstance().getCurrentUser()
- // add it only if it is not saved to database
- userId = user?.getUid()
- }
- private fun updateUser(name: String, email: String) {
- // updating the user via child nodes
- if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(email)) {
- mFirebaseDatabase!!.child(userId!!).child("name").setValue(name)
- mFirebaseDatabase!!.child(userId!!).child("email").setValue(email)
- Toast.makeText(applicationContext, "Successfully updated user", Toast.LENGTH_SHORT).show()
- }
- else
- Toast.makeText(applicationContext, "Unable to update user", Toast.LENGTH_SHORT).show()
- }
- fun onUpdateClicked(view: View) {
- val name = name.getText().toString()
- val email = email.getText().toString()
- //Calling updateUser function
- updateUser(name, email)
- }
- fun onDeleteClicked(view: View) {
- //Remove value from child
- mFirebaseDatabase!!.child(userId!!).removeValue()
- Toast.makeText(applicationContext, "Successfully deleted user", Toast.LENGTH_SHORT).show()
- // clear information
- txt_user.setText("")
- email.setText("")
- name.setText("")
- }
- companion object {
- private val TAG = upd_del::class.java.getSimpleName()
- }
- }
Output
Before Updating
After Updating
After deletion