Realtime Database using Firebase in Android App

Realtime Database using Firebase in Android App

Hello again!

I hope you found the last blog insightful. Now let us implement a Realtime Database into our application.

You can start reading the previous blog here if you do not know how to integrate Firebase with an Android application.

Prerequisite:

  • Basic knowledge of Android Studio.

  • Good understanding of basic Java and XML.

What is Realtime Database?

A real-time database is a database system that uses real-time processing to handle workloads whose state is constantly changing. The Firebase Realtime Database is a cloud-hosted database in which data is stored as JSON. The data is synchronized in real-time to every connected client. It is a NoSQL database from which we can store and sync the data between our users in real time. The developers can manage it as a big JSON object in real-time.

JSON Structured Data

The data stored in the Firebase Realtime Database is JSON structured i.e. the entire database will be a JSON tree with multiple nodes. So, unlike SQL databases, we don't have tables or records in the JSON tree. Whenever you are adding some data to the JSON tree, then it becomes a node in the existing JSON structure with some key associated with it. So, all Firebase Realtime Database data is stored as JSON objects. Following is an example of JSON-structured data:

{
    "student": {
        "name" : "Aastha",
        "address" : "India"
    }
}

Configure Realtime Database

Step-1: Go to the Firebase console > Firebase (project).

Step-2: Select Realtime Database > Create Database.

Step-3: Set up the database:

  • Set database location.

  • Set security rules: test mode (since we are working on dummy data, but for production application use locked mode)

Integrate Realtime Database to our Android App

Let us go back to our Android application. Go to Tools > Firebase > Realtime Database and connect the database (add dependencies).

Create activity_dashboard.xml, the UI should look like this:

You can find the XML code here: github.com/aasthamahindra/Firebase-Android/..

Create a model Artist.java:

package com.example.firebase;

public class Artist {

    String artistId, artistName, artistGenre;

    public Artist() {
    }

    public Artist(String artistId, String artistName, String artistGenre) {
        this.artistId = artistId;
        this.artistName = artistName;
        this.artistGenre = artistGenre;
    }

    public String getArtistId() {
        return artistId;
    }

    public void setArtistId(String artistId) {
        this.artistId = artistId;
    }

    public String getArtistName() {
        return artistName;
    }

    public void setArtistName(String artistName) {
        this.artistName = artistName;
    }

    public String getArtistGenre() {
        return artistGenre;
    }

    public void setArtistGenre(String artistGenre) {
        this.artistGenre = artistGenre;
    }
}

In Dashboard.java:

public class DashboardActivity extends AppCompatActivity {

    //Variables
    EditText nameET;
    AppCompatButton submitData;
    Spinner genreSpinner;

    DatabaseReference databaseArtists;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        //Hook all XML components
        nameET = findViewById(R.id.nameET);
        submitData = findViewById(R.id.addArtist);
        genreSpinner = findViewById(R.id.genreSpinner);

        databaseArtists =  FirebaseDatabase.getInstance().getReference("artist");

        //Save data to database
        submitData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addArtist();
                nameET.setText("");
            }
        });
        ...
    }

    private void addArtist(){

        String name = nameET.getText().toString().trim();
        String genre = genreSpinner.getSelectedItem().toString();

        if(!TextUtils.isEmpty(name)){
            String id = databaseArtists.push().getKey();

            Artist artist = new Artist(id, name, genre);
            assert id != null;
            databaseArtists.child(id).setValue(artist);

            Toast.makeText(this, "Artist Added", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this, "Enter name", Toast.LENGTH_SHORT).show();
        }
    }
}

Once you add the artist's name and click on Submit, go back to Firebase Console:

Conclusion

That’s the simplest solution for handling Firebase Realtime Database. I hope you found this article useful and if you have any questions regarding this topic, feel free and leave a comment in the section below.

Source Code: github.com/aasthamahindra/Firebase-Android

If you wanna support me, please follow me!

Happy Learning :)