Firebase provides a powerful API to store, retrieve and sync data in realtime, which paves way for an accelerated development reducing the pain of setting up your backend. In this post we will get a quick glance of making a CRUD with [Firebase Android SDK][firebase-android]. Firebase also provides you with a [Quick Start][firebase-quick-start] guide to get on with its SDKs.
Once you have an account with [Firebase][firebase], create an app and note down the app's URL. This app URL will be used in our android application as the base URL to firebase.
Adding Dependencies
app/build.gradle
Incase you end up with build errors,
Adding Permissions
app/src/main/AndroidManifest.xml
Necessary Layout Components
Two EditText components, a ListView and a Button. These EditText components holds the name(key) and the message(value) to be saved. Button is used to trigger the save action using Firebase sdk and a ListView to display the data.
Saving data on Firebase - Create
Declare necessary attributes.
The OnCreate Function
Adding click Listener to fire save action
We have saved our data to firebase and on our onComplete method above we empty the edittext boxes. So where do we actually read our data and update the view?
Read data from Firebase - Read
Firebase provides a ChildEventListener which pops up when ever a change occurs to the specified child to which the event is bound. In our case we bind it to the myFirebaseRef, which is commented out initially on our onCreate method.
Events which we could listen to are onChildAdded, onChildChanged, onChildRemoved, onChildMoved, onCancelled.
Whenever a new child is added onChildAdded will get triggered and the view is updated corresponding to the received data.
Listen for changes in the child - Update
As we had seen, the above code provides a method to listen on changes made to the child data. We update our code on onChildChanged method to publish updates and show it to the user.
Deleting a child - Delete
Now we uncomment itemClickListener for the listview. On click of an item in list view we delete the data based on the given name(Key).
And again we override the onChildRemoved function and update the view
You can find the source code of the entire sample over here, [Firebase CRUD][firebase-crud] with few miscellaneous functions,
[firebase]:https://www.firebase.com/
[firebase-android]:https://www.firebase.com/docs/android/
[firebase-quick-start]:https://www.firebase.com/docs/android/quickstart.html
[firebase-crud]:https://github.com/shrikanthkr/FirebaseCRUD