Skip to Content

Room Database CRUD in Android (Java) – Complete Guide

Introduction

Room Database is Google's official SQLite abstraction library for Android. It makes local database management easier, safer, and more efficient.

Without Room:

  • Complex SQL Queries

  • Boilerplate Code

  • SQLiteOpenHelper Management

With Room:

  • Simple CRUD Operations

  • Better Performance

  • Compile-Time Verification

  • Easy Integration with MVVM

In this tutorial, you will learn:

  • Room Database Setup

  • Create Entity

  • Create DAO

  • Create Database Class

  • Insert Data

  • Read Data

  • Update Data

  • Delete Data


What is Room Database?

Room is built on top of SQLite.

Architecture:

Entity
 ↓
DAO
 ↓
Room Database
 ↓
SQLite

Room handles most database operations automatically.


Prerequisites

Before starting:

  • Android Studio

  • Java Knowledge

  • Android Project


Step 1: Add Room Dependencies

app/build.gradle

implementation "androidx.room:room-runtime:2.6.1"
annotationProcessor "androidx.room:room-compiler:2.6.1"

Sync Project.


Step 2: Create Entity Class

Entity represents a database table.

User.java

import androidx.room.Entity;
import androidx.room.PrimaryKey;

@Entity(tableName = "users")
public class User {

    @PrimaryKey(autoGenerate = true)
    private int id;

    private String name;

    private String email;

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public String getEmail() {
        return email;
    }
}

Understanding Entity

@Entity(tableName = "users")

Creates:

CREATE TABLE users

Automatically.


Step 3: Create DAO Interface

DAO = Data Access Object

UserDao.java

import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;

import java.util.List;

@Dao
public interface UserDao {

    @Insert
    void insert(User user);

    @Update
    void update(User user);

    @Delete
    void delete(User user);

    @Query("SELECT * FROM users")
    List<User> getAllUsers();

}

DAO Operations

Insert

@Insert

Adds new record.


Update

@Update

Updates existing record.


Delete

@Delete

Deletes record.


Read

@Query("SELECT * FROM users")

Returns all users.


Step 4: Create Database Class

AppDatabase.java

import androidx.room.Database;
import androidx.room.RoomDatabase;

@Database(
        entities = {User.class},
        version = 1
)
public abstract class AppDatabase
        extends RoomDatabase {

    public abstract UserDao userDao();

}

Step 5: Initialize Database

MainActivity.java

import androidx.room.Room;

AppDatabase database =
        Room.databaseBuilder(
                getApplicationContext(),
                AppDatabase.class,
                "user_database"
        )
        .allowMainThreadQueries()
        .build();

Database created successfully.


Step 6: Insert Data

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

database
        .userDao()
        .insert(user);

Insert Button Example

btnSave.setOnClickListener(v -> {

    User user =
            new User(
                    etName.getText().toString(),
                    etEmail.getText().toString()
            );

    database
            .userDao()
            .insert(user);

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

});

Step 7: Read Data

List<User> userList =
        database
                .userDao()
                .getAllUsers();

Loop through data:

for(User user : userList){

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

}

Example Output

Anoj Kumar
Rahul
Amit
Rohit

Step 8: Update Data

First get user.

User user =
        userList.get(0);

Update:

user.setId(1);

database
        .userDao()
        .update(user);

Example:

User user =
        new User(
                "Updated Name",
                "updated@gmail.com"
        );

user.setId(1);

database
        .userDao()
        .update(user);

Step 9: Delete Data

database
        .userDao()
        .delete(user);

Deletes record instantly.


Delete Example

User user =
        userList.get(0);

database
        .userDao()
        .delete(user);

Delete All Users

Add DAO Method:

@Query("DELETE FROM users")
void deleteAll();

Usage:

database
        .userDao()
        .deleteAll();

Search User by ID

DAO:

@Query(
 "SELECT * FROM users WHERE id=:id"
)
User getUserById(int id);

Usage:

User user =
        database
                .userDao()
                .getUserById(1);

Search User by Name

DAO:

@Query(
 "SELECT * FROM users WHERE name=:name"
)
List<User> findUser(String name);

Usage:

List<User> users =
        database
                .userDao()
                .findUser("Anoj");

Complete CRUD Flow

Create

insert()

Read

getAllUsers()

Update

update()

Delete

delete()

Common Errors

Cannot Access Database

Cause:

Room.databaseBuilder()

not initialized.

Solution:

Initialize database first.


Annotation Processor Error

Cause:

room-compiler

missing.

Solution:

Add:

annotationProcessor "androidx.room:room-compiler:2.6.1"

App Crash

Cause:

Entity missing.

Solution:

Add:

@Entity

annotation.


Why Room is Better than SQLite?

SQLiteRoom
ComplexEasy
Manual QueriesAnnotations
More CodeLess Code
No ValidationCompile-Time Validation
Difficult CRUDEasy CRUD

Best Practices

✅ Use Room with MVVM

✅ Use Repository Pattern

✅ Use LiveData

✅ Use Background Threads

✅ Avoid allowMainThreadQueries() in production

✅ Create separate DAO for each table


Real World Use Cases

Room Database is used for:

  • Offline Notes Apps

  • To-Do Applications

  • Caching API Responses

  • E-Commerce Cart Storage

  • User Settings

  • Local Chat Storage


Room Architecture

Entity
 ↓
DAO
 ↓
Repository
 ↓
ViewModel
 ↓
Activity/Fragment

This is the recommended Android architecture.


Conclusion

Congratulations! 🎉

You have successfully implemented Room Database CRUD in Android using Java.

You learned:

  • Room Setup

  • Entity Creation

  • DAO Interface

  • Database Class

  • Insert Data

  • Read Data

  • Update Data

  • Delete Data

Room Database is one of the most important Android Jetpack components and is widely used in production applications.

Next Tutorial

  • Room Database with RecyclerView

  • Room Database with MVVM

  • Room + LiveData

  • Room + Retrofit Offline Cache

  • Room Database Search Feature

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.