Firebase Realtime Database CRUD Operation for Android

Hey guys here is the complete Firebase Realtime Database guide. Now days NoSQL databases are gaining popularity and Firebase Realtime Database is one of the NoSQL database.

In this tutorial we will learn modeling SQL tables to NoSQL Firebase Database. And then we will also learn the basic CRUD operation on the database (Create, Read, Update and Delete).

Firebase Realtime Database Video Tutorial

  • If you are more comfortable in learning with video tutorials, then here is the video tutorial series for Firebase Realtime Database.

Designing Database

  • For this example I have following two tables.

database

  • But firebase is not an SQL database and it does not stores data in tabular format. It uses JSON tree structure. So for firebase realtime database the structure for above database will be.

firebase realtime database

  • I hope you got a clear understanding of the Firebase Realtime Database structure now. So lets jump into Android Studio.

Firebase Realtime Database Basics

  • You have the database structure now you need to know the basic operations. So lets understand the steps of handling firebase database.

Getting Database Reference

  • First we need to get the Firebase Database Reference. You can use DatabaseReference to get the reference.

  • The data is stored in the JSON Tree form so you need to get the reference of an specified path. Like in the above database we can get all the Artists by passing “Artists”. If you want to access everything don’t pass anything and it will create a reference of the root of the tree.

Write Operation

  • setValue() – This method will take a model java class object that will hold all the variables to be stored in the reference. The same method will be used to update the values at it overwrites the data of the specified reference.  
  • Suppose we have to store an Artist to our reference then we will create a model class as below.

  • Now to save the artist we will use setValue() method.

  • The update operation will also be done in the same way.

Read Operation

  • We will attache a ValueEventListener to the reference to read the data.

  • Whenever you will change something in the Database the method onDataChange() will be executed. It contains all the data inside the specified path in the reference. We can use the DataSnapshot object to read all the data inside the reference.  If some error occurres onCancelled() method will be called.
  • onDataChange() method will also called once after the app launch and hence you can read the data at starting as well.

Delete Operation

  • removeValue() can be used to delete the data.
  • Now lets understand the operations in an Android Project.

Firebase Realtime Database Project

Creating Android Studio Project

  • Open Android Studio and create a new project. In my case I have created FirebaseDatabaseExample.
  • Now once your project is loaded completely, add Firebase Database in it.

Adding Firebase Database

  • Go to tools -> Firebase, it will open an assistant. Now from the assistant go to Realtime Database.

realtime database

  • Connect to your Firebase Project and Setup the dependencies.

save and retrieve data

  • Now you are ready to use Firebase Database in your project.

Creating Activity Layouts

  • We need two activities. One is to add Artists and other one is to add Tracks to database. We will use MainActivity.java and activity_main.xml for Artists. But you need to create one more activity for Tracks. So I have created ArtistActivity and activity_artist.xml. 
  • Now first come inside activity_main.xml. Here we will create the following layout.

artist

  • As you can see the layout contains the following thing.
    EditText: Here we will enter the name.
    Spinner: Here we will give some genres so that we can select one of them.
    Button: To save the new artist in Firebase.
    ListView: To display all the saved artist from Firebase.
  • For creating this layout you can use the following xml code.

  • For ArtistsActivity we will create almost the same layout with little changes. So this activity will be like.

artist_activity

  • For this activity you can again use the following xml.

  • Now lets save the data in Firebase. But before proceeding in save operation we need to define the Models for Artist and Track.

Defining Models

  • Create a java class named Artist and write the following code.

  • Now again create one more class named Track and write the following code.

  • Now lets save an artist to the database.

Saving an Artist

  • Come inside MainActivity.java and write the following code.

  • Now try running the application.

saving data firebase

  • The toast is fine now lets check the database.

firebase realtime database

  • So we the artist is getting save. Everytime you will save an artist a new child node inside artists will be created with a unique id.

Retrieving Artists

  • Now we will fetch all the artists. We already have the ListView to display all the artists with genre. But before proceeding in retrieving the artists in ListView we will create a Layout File and a Custom Adapter for the list.
  • So first create a new layout file named layout_artist_list.xml it will contain two TextView.

  • Now create one more class named ArtistList and write the following code.

  • Now lets retrieve all the artists. For this we will attach a ValueEventListener to the database reference object, inside onStart() method of MainActivity.

  • Now again run the application.

firebase realtime database

  • So the Artists are getting fetched. Also if you will add new Artist it will be automatically added inside the ListView as the method onDataChange() will be executed on any data change.
  • Now we will add Tracks to a particular Artist. For this we will open a new Activity when an Artist is selected from the ListView. For this we have to attach an OnItemClickListener to the ListView.
  • So add the following code inside onCreate() method.

  • Now run your application and select an Artist from the List. A new activity will open displaying the artist name.

firebase realtime database

  • Now lets proceed in adding and retrieving tracks. But before we need to create one more class for the adapter of Track List.
  • So create a new class named TrackList and write the following code.

  • Now lets add and retrieve tracks.

Adding and Retrieving Tracks from Firebase Realtime Database

  • Come inside ArtistActivity.java and write the following code. The process is same as we did above that is why I am not explaining the codes with comments.

  • Again run your application and try adding tracks.

firebase realtime database

  • As you can see tracks are getting saved. Now lets see updating the Artist.

Updating Artist in Firebase Database

  • For updating an existing artist name or genre we will show a Dialog to enter new detail. Dialog will be opened on long pressing an Artist from the list.
  • So first create a new layout file named update_dialog.xml and write the following xml code. The same dialog will be used for deleting the artist as well.

  • As you can see we have two buttons one to update the artist and other one to delete the artist.
  • Now come inside MainActivity.java and define a method updateArtist().

  • Define one more method named showUpdateDeleteDialog(). In this method we are building a Dialog and on update button click we are calling the above method updateArtist() to update the artist.

  • Now inside onCreate() attach an OnItemLongClickListener to the ListView. And on LongClick we will call the method showUpdateDeleteDialog().

  • Now again try running the application. Long press on an Artist and try updating it.

firebase realtime database

  • So the update is working fine. Now only the delete operation is remaining. So lets delete an Artist.

Deleting Artist from Firebase Realtime Database

  • Remember when we delete an Artist all the tracks of that particular Artist should be deleted as well.
  • So define a method deleteArtist() inside MainActivity.

  • Now call this method inside Click Listener of Delete Artist Button which is inside showUpdateDeleteDialog(). 

  • Now run your application and try deleting an Artist.

deleting firebase data

  • Bingo! the delete is working fine as well. If you are having troubles about this Firebase Realtime Database Tutorial you can get my source code from below.

Firebase Realtime Database CRUD

So thats all for this Firebase Realtime Database tutorial. We covered all the operations like Creating, Reading, Updating and Deleting (CRUD) data in Firebase Realtime Database. If you are having any queries and confusions then lets discuss in comment section.

33 thoughts on “Firebase Realtime Database CRUD Operation for Android”

  1. Great explanation, thanks a lot.
    How can we have load more on scroll with this? While loading only few (may be 5) on every scroll.

    Reply
  2. Thanks for tutorial Belal Khan.
    I have a question: I want to make a search (android.support.v7.widget.SearchView) on this realtime database and I’m new on android development. I tried this;

    @Override
    @TargetApi(Build.VERSION_CODES.N_MR1)
    public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.option_search, menu);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView search = (SearchView) menu.findItem(R.id.search).getActionView();
    search.setSearchableInfo(manager.getSearchableInfo(getComponentName()));

    search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
    return false;
    }

    @Override
    public boolean onQueryTextChange(String newText ) {

    //creating adapter
    ArtistList artistAdapter = new ArtistList(FireBaseMain.this, artists);
    //attaching adapter to the listview
    listViewArtists.setAdapter(artistAdapter);
    artistAdapter.getFilter().filter(newText);

    return false;
    }
    });

    }
    return true;
    }
    but this wasn’t succeed. Could you lead me about, how can we make query on our database? Thank you.

    Reply
  3. thank you for the tutorial. I want to ask a question. how can we query an artist and show it a textview (equivalent of select * from artist whe name=”atif aslam”)?

    Reply
  4. thankyou for this tutorial.
    but i have a question, is there a way to select all of tracks data without choose artist data first? thx..

    Reply
  5. Thanks a lot for this amazing tutorial! But there is one problem I’m having using your tutorial, I added an authentication, so I wanted each user to see only what they saved, instead all users receive the same data from firebase, so what can I do to change this so that each user receives only what they saved? Thanks!

    Reply
  6. Thanks for the wonderful tutorial!!

    I was wondering what if i need to store album cover (i.e., and image) as well??? It would be a great help if you can guide.

    Reply
  7. does it works fine if a generate an apk file of the application. And when the user adds the data can i get the data in the same database.

    Reply
  8. how can i add more child nodes to a specific path with previously added artist data

    should i create another model class for the data which i need to add

    eg: here you hv added artist data through a model class
    how can i add more data to this artist class by specifying a particular artist

    any help is appreciated

    Reply
  9. Please do add how to save the star rating into the firebase. Really need help on this since i didnt found any tutorial related to it.

    Reply
  10. Hi,
    I have a question, do you know how to change spinner in a way to hide used item?
    I changed my application to rate food and where you have rating and a place to write text, i put spinner.
    It’s about choose for example taste a rate it for 9, color and rate it for 5… etc. How can i make spinner to forget used item for example taste, if it is already rated?

    Reply
  11. how to integerated realtime database with firebase storage ?, so we can upload image and integerating with data in realtime database.

    Reply
  12. Hello, please help me firebase store and retrieve data, my problem here-

    I have an app, in which user logged in with gmail id and click on taskone button. here on button click
    i want to give reward (10 coins) to user each time. now i want
    to store these coins in taskone_score.
    again click on tasktwo button. on button click i want to give reward (10 coins) to user each time. now i want
    to store total coins in firebase (total_score).
    again next day when user sign in, total score retrieve
    from firebase database and show on activity page above both buttons.
    Store data in firebase like this-

    – email
    -total_score (coins)
    -taskone_score (coins)
    -tasktwo_score (coins)

    Reply
  13. When I follow the above code app is running successfully and even toast message is also shown but when I press on artist to view the list there is no list and even in the database not showing any object.

    Reply
  14. Hi bro, all are working perfectly
    I want update and delete tracks but is not working

    can you please give me a help

    Reply

Leave a Comment