Android Create Delete in Firebase Realtime Database & Storage

In almost all of the applications there is a requirement to save or store data in database. In Android we can use SQLite database or database hosted remotely. Google Firebase provides real time database access that can be implemented for all the CRUD activities. In previous articles we discussed how to connect Android application with Firebase realtime database. In another article we saw how to display images from firebase storage and Firebase Cloud Functions. Now we will extend those examples with write and update operations. By the end of this article we will learn basic CRUD (Create, Read, Update and Delete) operations using Firebase Realtime Database.

In this example we will take use of Firebase Storage to upload User uploaded images and save path in database to display in list view.

 

Flow

  1. Fetch user data from database and display in recycler view
  2. User selects and upload image to Firebase Storage
  3. On successfully upload of image, save path in Firebase Database
  4. Refresh new data

Create JSON POJO classes:

Create java POJO class for our database.

UserImageList

User Image Data

Read data from Database:

Read user saved data from the database to show in recycler view. Check out this article to find out how to display images stored in cloud storage.

If the data needs to be read only once then use SingleValueEvent listener.

If continuous updates are desired then use ChildEvent listener to listen to onChildAdded event.

ChildEventListener onChildAdded()
Retrieve lists of items or listen for additions to a list of items. This callback is triggered once for each existing child and then again every time a new child is added to the specified path. The DataSnapshot passed to the listener contains the the new child’s data.

 

Select and upload image to Storage

Firebase Storage Rule

Update rules of Firebase Storage to support write operation.

Android upload code snippet

Save and upload user selected image to firebase storage

Convert selected image to byte array by converting and compressing bitmap to binary format.

Save converted bitmap to firebase storage bucket.

 

Update File Metadata in Database:

Get storage reference url of the uploaded image and save path in database.

The reason why we have saved image paths in the database is because firebase storage do not provide any api to list files or folders. The only way to get the storage files is by keeping an index of files in our database.

Delete file from Storage and File entry from Database:

Let’s see how to delete an item from storage as well as database.

 

If you are facing permission issues or failure to upload data to storage/database then do check the rules tab in firebase dashboard.

 

FirebaseDatabaseStorage
FirebaseDatabaseStorage
FirebaseDatabaseStorage.zip
215.4 KiB
75 Downloads
Details

Leave a Reply