ROOM Database is the ORM (Object Relational Mapper) library for Android development.
It is used to map database objects to Java objects.
ROOM provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite. i.e., it makes it possible to access a database without the need of writing SQL queries.
Room database has three main components:
Entity
DAO (Data Access Object)
Database
In order to implement Room in the Android development, you need to follow the following workflow:
Add ROOM dependency
Go to https://developer.android.com/jetpack/androidx/releases/room , then copy the following dependency and paste in build.gradle.kts
in your Android project in the dependencies section
val room_version = "2.6.1"
implementation("androidx.room:room-runtime:$room_version")
annotationProcessor("androidx.room:room-compiler:$room_version")
The whole sample dependencies are as follows:
dependencies {
val room_version = "2.6.1"
implementation("androidx.room:room-runtime:$room_version")
annotationProcessor("androidx.room:room-compiler:$room_version")
implementation(libs.appcompat)
implementation(libs.material)
implementation(libs.activity)
implementation(libs.constraintlayout)
testImplementation(libs.junit)
androidTestImplementation(libs.ext.junit)
androidTestImplementation(libs.espresso.core)
}
Create the Entity
Entity is a class that represents a table within the ROOM database.
Each instance of an entity class corresponds to a single row in that table, with each field in that class representing a column.
It must be annotated with @Entity
package com.example.contactapp;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity(tableName = "contact")
public class Contact {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name="contact_id")
int id;
@ColumnInfo(name = "first_name")
String firstName;
@ColumnInfo(name = "last_name")
String lastName;
@ColumnInfo(name="user_mail")
String email;
}
Create the DAO
DAO is the short form for Data Access Object. It is an interface that defines the set of methods for accessing and manipulating data in the database. It must be annotated with @Dao
package com.example.contactapp;
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 ContactDao {
@Query("SELECT * FROM contact")
List<Contact> getAllContact(Contact contact);
@Update
void updateContact(Contact contact);
@Delete
void deleteContact(Contact contact);
@Insert
void getContact();
}
Create the Room Database Instance
It is the abstract class that extends RoomDatabase and serves as the main access point to the SQLite database and links the DAOs and entities together.It must be annotated with @Database
package com.example.contactapp;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
@Database(version = 1,entities = {Contact.class})
public abstract class ContactDatabase extends RoomDatabase {
public abstract ContactDao getContactDao();
private static ContactDatabase dbInstance;
public static synchronized ContactDatabase getDbInstance(Context
context){
if (dbInstance != null){
dbInstance = Room.databaseBuilder(
context.getApplicationContext(),
ContactDatabase.class,
"contact_db"
).fallbackToDestructiveMigration().build();
}
return dbInstance;
}
}
Create Repository (Optional)
The repository is the class that manages multiple resources of data.
It acts as an intermediary between data sources and ViewModel in the MVVM architecture.
It gathers data from different sources such as:
REST APIs
Cache
Local database storage
... and then provides the data to the rest of the application.
package com.example.contactapp;
import android.app.Application;
import android.os.Handler;
import android.os.Looper;
import androidx.lifecycle.LiveData;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Repository {
public final ContactDao contactDao;
ExecutorService executer;
Handler handler;
public Repository(Application application) {
ContactDatabase contactDatabase = ContactDatabase.getDbInstance(application);
this.contactDao = contactDatabase.getContactDao();
// Used for background operations
executer = Executors.newSingleThreadExecutor();
// Used for updating UI
handler = new Handler(Looper.getMainLooper());
}
public void updateContact(Contact contact){
executer.execute(new Runnable() {
@Override
public void run() {
contactDao.updateContact(contact);
}
});
}
public void deleteContact(Contact contact){
executer.execute(() -> contactDao.deleteContact(contact));
}
public void insertContact(Contact contact){
executer.execute(new Runnable() {
@Override
public void run() {
contactDao.insertContact(contact);
}
});
}
public LiveData<List<Contact>> getAllContacts(){
return contactDao.getAllContact();
}
}
Top comments (0)