Skip to Content

Firebase Realtime Database in Android (Java) – Complete CRUD Tutorial

 

Introduction

Firebase Realtime Database is a cloud-hosted NoSQL database that allows you to store and sync data in real-time across all connected clients.

It is one of the most popular Firebase services used in Android applications because it is easy to integrate and automatically synchronizes data whenever changes occur.

In this tutorial, you will learn:

  • Firebase Realtime Database Setup

  • Add Data

  • Read Data

  • Update Data

  • Delete Data

  • Real-Time Data Synchronization

  • Complete CRUD Operations


What is Firebase Realtime Database?

Firebase Realtime Database stores data in JSON format.

Example:

{
  "users": {
    "user1": {
      "name": "Anoj",
      "email": "anoj@gmail.com"
    }
  }
}

Whenever data changes:

  • Mobile App updates instantly

  • Web updates instantly

  • Other users receive updates instantly

without refreshing the application.


Prerequisites

Before starting:

  • Android Studio installed

  • Firebase Project created

  • Firebase connected with Android App

  • Internet connection


Step 1: Create Firebase Project

  1. Open Firebase Console

  2. Click Create Project

  3. Enter Project Name

  4. Finish setup


Step 2: Connect Android App

  1. Add Android App

  2. Enter Package Name

Example:

com.palcoder.realtimedatabase
  1. Download:

google-services.json
  1. Place it inside:

app/

folder.


Step 3: Enable Realtime Database

Firebase Console

Build

Realtime Database

Create Database

Start in Test Mode

Enable


Step 4: Add Dependency

App Level build.gradle

implementation 'com.google.firebase:firebase-database:21.0.0'

Sync Project.


Step 5: Create User Model Class

Create:

User.java
public class User {

    String name;
    String email;

    public User() {
    }

    public User(String name, String email) {
        this.name = name;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public String getEmail() {
        return email;
    }

}

Step 6: Create Layout

activity_main.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="16dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/etName"
        android:hint="Name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <EditText
        android:id="@+id/etEmail"
        android:hint="Email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/btnSave"
        android:text="Save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

Step 7: Initialize Database

MainActivity.java

DatabaseReference databaseReference;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    databaseReference =
            FirebaseDatabase
                    .getInstance()
                    .getReference("Users");
}

Step 8: Insert Data

String id = databaseReference.push().getKey();

User user =
        new User(
                "Anoj Kumar",
                "anoj@gmail.com"
        );

databaseReference
        .child(id)
        .setValue(user);

Full Save Button Example

btnSave.setOnClickListener(v -> {

    String name =
            etName.getText().toString();

    String email =
            etEmail.getText().toString();

    String id =
            databaseReference.push().getKey();

    User user =
            new User(name,email);

    databaseReference
            .child(id)
            .setValue(user)
            .addOnSuccessListener(unused -> {

                Toast.makeText(
                        MainActivity.this,
                        "Data Saved",
                        Toast.LENGTH_SHORT
                ).show();

            });

});

Database Output

Firebase Database

{
  "Users": {
    "-OABC123": {
      "name": "Anoj Kumar",
      "email": "anoj@gmail.com"
    }
  }
}

Step 9: Read Data

databaseReference
        .addValueEventListener(
                new ValueEventListener() {

            @Override
            public void onDataChange(
                    @NonNull DataSnapshot snapshot) {

                for(DataSnapshot ds :
                        snapshot.getChildren()) {

                    User user =
                            ds.getValue(
                                    User.class
                            );

                    Log.d(
                            "DATA",
                            user.getName()
                    );

                }

            }

            @Override
            public void onCancelled(
                    @NonNull DatabaseError error) {

            }

        });

Read Single User

databaseReference
        .child(userId)
        .get()
        .addOnSuccessListener(snapshot -> {

            User user =
                    snapshot.getValue(
                            User.class
                    );

        });

Step 10: Update Data

databaseReference
        .child(userId)
        .child("name")
        .setValue("Updated Name");

Update Multiple Fields

HashMap<String,Object> map =
        new HashMap<>();

map.put("name","Rahul");
map.put("email","rahul@gmail.com");

databaseReference
        .child(userId)
        .updateChildren(map);

Step 11: Delete Data

databaseReference
        .child(userId)
        .removeValue();

Data will be removed instantly.


Real-Time Updates

Whenever data changes:

  • New user added

  • User updated

  • User deleted

all connected devices automatically receive updates.

No refresh button needed.


Firebase Security Rules

Development:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

⚠ Only for testing.


Production Rules

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

Only authenticated users can access data.


Common Errors

Permission Denied

Permission denied

Solution:

Check Firebase Rules.


Database URL Error

Database not found

Solution:

Verify Firebase project setup.


Null Pointer Exception

user.getName()

returns null.

Solution:

Add empty constructor in model class.


Best Practices

✅ Use Authentication

✅ Secure Database Rules

✅ Use Model Classes

✅ Validate User Input

✅ Avoid Public Read/Write Rules

✅ Use push() for unique IDs


Complete CRUD Summary

Create

setValue()

Read

addValueEventListener()

Update

updateChildren()

Delete

removeValue()

Conclusion

Congratulations! 🎉

You have successfully learned how to use Firebase Realtime Database in Android using Java.

You can now:

  • Store data

  • Read data

  • Update records

  • Delete records

  • Synchronize data in real time

Realtime Database is ideal for:

  • Chat Apps

  • Social Apps

  • Live Dashboards

  • Real-Time Tracking

  • Multiplayer Games

Next Tutorial

  • Firebase Storage Upload Image (Java)

  • Firebase Firestore Database

  • Firebase Phone Authentication

  • Firebase Push Notifications (FCM)

  • Firebase Email Verification

Disclaimer: The information, code snippets, and tutorials presented on this website are for educational and informational purposes only. While we make every effort to provide accurate, tested, and high-quality contents, all materials are provided "as is" without warranty of any kind. Use them at your own discretion and risk.

Enjoyed this tutorial?

Consider supporting Pal Coder so we can keep creating high-quality, free Android development resources.