Javatpoint Logo
Javatpoint Logo

Firebase: Realtime Database Update and Delete

In our previous section, 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.

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

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 we want to know when our data has been committed, we 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.

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

Output

Firebase: Realtime Database Update and Delete

Before Updating

Firebase: Realtime Database Update and Delete

After Updating

Firebase: Realtime Database Update and Delete

After deletion

Firebase: Realtime Database Update and Delete

Next TopicFirestore




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA