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
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:
Here's a step-by-step guide to performing CRUD operations using Room:
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"
@Entity(tableName = "note_table") public class Note { @PrimaryKey(autoGenerate = true) private int id; private String title; private String description; // Constructors, getters, setters }
@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(); }
@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; } }
Note newNote = new Note("Title", "Description"); noteDao.insert(newNote);
LiveData<List<Note>> allNotes = noteDao.getAllNotes(); allNotes.observe(this, notes -> { // Update UI or RecyclerView });
note.setTitle("New Title"); noteDao.update(note);
noteDao.delete(note);
noteDao.deleteAllNotes();
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.
Room Persistence Library CRUD operations example:
// 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(); }
Android Room Database insert update delete select 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);