Room Database Tutorial
Introduction to Room Database
Room is a persistence library that provides an abstraction layer over SQLite to allow for more robust database access while harnessing the full power of SQLite. Using Room helps you minimize repetitive and error-prone boilerplate code and provides compile-time verification of SQL queries.
Setting Up Room in Your Project
To use Room in your Android application, you need to add the Room dependencies to your build.gradle file:
dependencies { def room_version = "2.3.0" implementation "androidx.room:room-runtime:$room_version" annotationProcessor "androidx.room:room-compiler:$room_version" }
Creating an Entity
An entity represents a table within the database. Each field in the entity represents a column in the table.
@Entity(tableName = "user") public class User { @PrimaryKey(autoGenerate = true) public int uid; @ColumnInfo(name = "first_name") public String firstName; @ColumnInfo(name = "last_name") public String lastName; }
Creating a DAO
The Data Access Object (DAO) is an interface that defines the methods for accessing the database. These methods can include queries, insertions, updates, and deletions.
@Dao public interface UserDao { @Query("SELECT * FROM user") ListgetAllUsers(); @Insert void insertUser(User user); @Delete void deleteUser(User user); }
Creating the Database
The database class is an abstract class that extends RoomDatabase. It serves as the main access point to your persisted data.
@Database(entities = {User.class}, version = 1) public abstract class AppDatabase extends RoomDatabase { public abstract UserDao userDao(); }
To create an instance of the database, use the Room.databaseBuilder() method:
AppDatabase db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "database-name").build();
Using the Room Database
Once you have set up the database, you can start performing database operations. For example, to insert a user into the database:
User user = new User(); user.firstName = "John"; user.lastName = "Doe"; db.userDao().insertUser(user);
To retrieve all users from the database:
Listusers = db.userDao().getAllUsers();
Conclusion
In this tutorial, we covered the basics of using Room database in an Android application, including setting up Room, creating entities, DAOs, and the database itself, as well as performing basic database operations. Room provides a powerful and efficient way to manage local data in your Android apps with minimal boilerplate code.