Android Tutorial

Software Setup and Configuration

Android Studio

File Structure

Components

Core Topics

Layout

View

Button

Intent and Intent Filters

Toast

RecyclerView

Fragments

Adapters

Other UI Component

Image Loading Libraries

Date and Time

Material Design

Bars

Working with Google Maps

Chart

Animation

Database

Advance Android

Jetpack

Architecture

App Publish

App Monetization

How to Perform CRUD Operations in Room Database in Android?

The Room persistence library provides an abstraction layer over SQLite to allow for more robust database access while harnessing the full power of SQLite. To perform CRUD (Create, Read, Update, Delete) operations using Room, you'll need to set up three main components:

  1. Entity: Represents a table within the database.
  2. DAO (Data Access Object): Contains methods that provide access to your app's database.
  3. Database: Contains the database holder and serves as the main access point for the underlying connection to your app's persisted data.

Here's a step-by-step guide to performing CRUD operations using Room:

1. Add Dependencies:

Firstly, add the necessary Room dependencies in your app's build.gradle:

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

2. Define an Entity:

@Entity(tableName = "note_table")
public class Note {
    
    @PrimaryKey(autoGenerate = true)
    private int id;

    private String title;
    private String description;

    // Constructors, getters, setters
}

3. Create a DAO:

@Dao
public interface NoteDao {

    @Insert
    void insert(Note note);

    @Update
    void update(Note note);

    @Delete
    void delete(Note note);

    @Query("DELETE FROM note_table")
    void deleteAllNotes();

    @Query("SELECT * FROM note_table ORDER BY id DESC")
    LiveData<List<Note>> getAllNotes();
}

4. Define the Database:

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

    private static NoteDatabase instance;

    public abstract NoteDao noteDao();

    public static synchronized NoteDatabase getInstance(Context context) {
        if (instance == null) {
            instance = Room.databaseBuilder(context.getApplicationContext(),
                    NoteDatabase.class, "note_database")
                    .fallbackToDestructiveMigration()
                    .build();
        }
        return instance;
    }
}

5. Implement CRUD Operations:

  • Create (Insert):
Note newNote = new Note("Title", "Description");
noteDao.insert(newNote);
  • Read (Get All Notes):
LiveData<List<Note>> allNotes = noteDao.getAllNotes();
allNotes.observe(this, notes -> {
    // Update UI or RecyclerView
});
  • Update:
note.setTitle("New Title");
noteDao.update(note);
  • Delete:
noteDao.delete(note);
  • Delete All Notes:
noteDao.deleteAllNotes();

6. Execute Database Operations on a Non-UI Thread:

Since Room doesn't allow database operations on the main thread (as it can lock the UI), you should execute these operations on a separate thread. Use AsyncTask, Executors, RxJava, or Kotlin coroutines for this purpose.

For instance, using AsyncTask:

public class InsertNoteAsyncTask extends AsyncTask<Note, Void, Void> {

    private NoteDao noteDao;

    private InsertNoteAsyncTask(NoteDao noteDao) {
        this.noteDao = noteDao;
    }

    @Override
    protected Void doInBackground(Note... notes) {
        noteDao.insert(notes[0]);
        return null;
    }
}

// To use
new InsertNoteAsyncTask(noteDao).execute(note);

However, AsyncTask is deprecated in later versions of Android. In production apps, you'd more likely use another method like Executors, RxJava, or Kotlin coroutines.

With this setup, you can perform basic CRUD operations using Room in your Android app. You can expand upon this foundation by adding more complex queries, relationships between entities, migrations, and so on.

  1. Room Persistence Library CRUD operations example:

    • Create an Entity class representing the data structure, a DAO interface with methods for CRUD operations, and a Room Database class.
    // Step 1: Define Entity
    @Entity
    public class Note {
        @PrimaryKey(autoGenerate = true)
        public long id;
    
        public String title;
        public String content;
    }
    
    // Step 2: Define DAO
    @Dao
    public interface NoteDao {
        @Insert
        void insert(Note note);
    
        @Query("SELECT * FROM Note")
        List<Note> getAllNotes();
    
        @Query("SELECT * FROM Note WHERE id = :noteId")
        Note getNoteById(long noteId);
    
        @Update
        void update(Note note);
    
        @Delete
        void delete(Note note);
    }
    
    // Step 3: Define Room Database
    @Database(entities = {Note.class}, version = 1)
    public abstract class AppDatabase extends RoomDatabase {
        public abstract NoteDao noteDao();
    }
    
  2. Android Room Database insert update delete select example:

    • Use the defined Room components to perform CRUD operations. Here's an example:
    // Inside your activity or repository
    // Instantiate Room Database
    AppDatabase database = Room.databaseBuilder(context, AppDatabase.class, "notes-db").build();
    
    // Insert
    Note newNote = new Note();
    newNote.title = "New Note";
    newNote.content = "This is a new note.";
    database.noteDao().insert(newNote);
    
    // Read/Select All
    List<Note> allNotes = database.noteDao().getAllNotes();
    
    // Read/Select by Id
    long noteIdToRetrieve = 1; // Replace with the actual noteId
    Note retrievedNote = database.noteDao().getNoteById(noteIdToRetrieve);
    
    // Update
    retrievedNote.content = "Updated content.";
    database.noteDao().update(retrievedNote);
    
    // Delete
    database.noteDao().delete(retrievedNote);