Firebase: Realtime Database Update and Delete FIREBASE

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.

  1. correct child reference.   
  2. myRef.setValue("Hello, World")  
  3. 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

  1. //writeNewPost function for chat application  
  2. private fun Newpost(userId:String, username:String, title:String, body:String){  
  3.     //creating new post at /user-posts/$userid/$postid simultaneously  
  4.     //Using push key  
  5.     val key=database.child("posts").push().key  
  6.     //Checking it is null or not  
  7. if(key==null){  
  8.         Log.w(TAG,"Could not get push key for posts")  
  9.         return  
  10.     }  
  11.     //Creating Post object  
  12.     val post=Post(userId, username, title, body)  
  13.     //Push it to a map  
  14. val postValues=post.toMap()  
  15.     val childUpdates=HashMap<String,Any>()  
  16.     childUpdates["/posts/$key"]=postValues  
  17.     childUpdates["/user-posts/$userId/$key"]=postValues  
  18.     database.updateChildren(childUpdates)  
  19. }  

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.

 
  1. database.child("users").child(userId).setValue(user)  
  2.     .addOnSuccessListener{  
  3.         //Write was successful!  
  4.         //?.  
  5.     }  
  6. .addOnFailureListener{  
  7.         //Write failed  
  8.         //?  
  9. }

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

  1. package com.example.firebaserealtimedatabase  
  2.   
  3. import androidx.appcompat.app.AppCompatActivity  
  4. import android.os.Bundle  
  5. import android.text.TextUtils  
  6. import android.util.Log  
  7. import android.view.View  
  8. import android.widget.Toast  
  9. import com.google.firebase.auth.FirebaseAuth  
  10. import com.google.firebase.database.*  
  11. import kotlinx.android.synthetic.main.activity_upd_del.*  
  12. import kotlinx.android.synthetic.main.activity_welcome.*  
  13. import kotlinx.android.synthetic.main.activity_welcome.email  
  14.   
  15. class upd_del : AppCompatActivity() {  
  16.   
  17.     private var mFirebaseDatabase: DatabaseReference? = null  
  18.         private var mFirebaseInstance: FirebaseDatabase? = null  
  19.   
  20.         private var userId: String? = null  
  21.   
  22.         override fun onCreate(savedInstanceState: Bundle?) {  
  23.             super.onCreate(savedInstanceState)  
  24.             setContentView(R.layout.activity_upd_del)  
  25.   
  26.             mFirebaseInstance = FirebaseDatabase.getInstance()  
  27.   
  28.             // get reference to 'users' node  
  29.             mFirebaseDatabase = mFirebaseInstance!!.getReference("users")  
  30.   
  31.             val user = FirebaseAuth.getInstance().getCurrentUser()  
  32.   
  33.             // add it only if it is not saved to database  
  34.             userId = user?.getUid()  
  35.   
  36.         }  
  37.   
  38.   
  39.         private fun updateUser(name: String, email: String) {  
  40.             // updating the user via child nodes  
  41.             if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(email)) {  
  42.                 mFirebaseDatabase!!.child(userId!!).child("name").setValue(name)  
  43.                 mFirebaseDatabase!!.child(userId!!).child("email").setValue(email)  
  44.                 Toast.makeText(applicationContext, "Successfully updated user", Toast.LENGTH_SHORT).show()  
  45.             }  
  46.             else  
  47.                 Toast.makeText(applicationContext, "Unable to update user", Toast.LENGTH_SHORT).show()  
  48.   
  49.         }  
  50.   
  51.         fun onUpdateClicked(view: View) {  
  52.             val name = name.getText().toString()  
  53.             val email = email.getText().toString()  
  54.   
  55.             //Calling updateUser function   
  56.             updateUser(name, email)  
  57.         }  
  58.   
  59.         fun onDeleteClicked(view: View) {  
  60.             //Remove value from child   
  61.             mFirebaseDatabase!!.child(userId!!).removeValue()  
  62.             Toast.makeText(applicationContext, "Successfully deleted user", Toast.LENGTH_SHORT).show()  
  63.   
  64.             // clear information  
  65.             txt_user.setText("")  
  66.             email.setText("")  
  67.             name.setText("")  
  68.         }  
  69.   
  70.         companion object {  
  71.             private val TAG = upd_del::class.java.getSimpleName()  
  72.         }  
  73.     }  

 

Output

Before Updating

After Updating

After deletion

#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries