There are several databases that can be used in Android, including SQLite, Room, and Firebase Realtime Database.
In this article, you will learn how to perform a simple database operation using Android Room.
What is Android Room?
Android Room is a database management tool designed for using SQLite database in the Android platform. Room makes it easier and safer to use SQLite database and helps you perform database operations in a more structured manner.
Room converts the data in the database into Java objects and allows you to perform database operations on these objects. This makes database operations more readable and understandable and helps prevent errors. Room also makes it easier to manage changes between different versions of the database and makes updating the database easier.
Room can also work with functions such as LiveData and RxJava, allowing the asynchronous reading and updating of data in the database.
In short, Android Room is an easy-to-use and secure database management tool for developers who want to use a database in the Android platform.
How to Add Android Room to a Project?
To add Android Room to an Android project, follow the steps below:
Step 1: Go to the project directory and go to the app/build.gradle file to add the Room library to your Gradle file. Add the following lines inside the dependencies block:
1 2 3 4 5 6 7 8 9 10 11 |
.... dependencies { def room_version = "2.5.0" implementation "androidx.room:room-runtime:$room_version" annotationProcessor "androidx.room:room-compiler:$room_version" .... |
Step 2: Create a model class for the database. The model class defines a table in the database as a Java object. For example, you can create a user model class like the following:
Student.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
package com.example.myapplication; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; @Entity public class Student { @PrimaryKey(autoGenerate = true) private int id; @ColumnInfo(name = "student_name") private String name; @ColumnInfo(name = "student_email") private String email; public Student(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 void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } |
Step 3: Create a DAO (Data Access Object) class to access the data in the database. The DAO class defines the operations for reading, writing, updating and deleting the data in the database. For example, you can create a student DAO class as follows:
StudentDAO.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package com.example.myapplication; 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 StudentDao { @Insert void insert(Student student); @Query("SELECT * FROM student") List<Student> getAll(); @Update void update(Student student); @Delete void delete(Student student); @Query("SELECT * FROM student WHERE student_email= :mail") List<Student> getStudentByMail(String mail); } |
Step 4: Define the database. The database is defined as a class that is derived from the RoomDatabase class. The database class defines the DAO class and the database version. For example, you can create a database class as follows:
AppDatabase.java
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.example.myapplication; import androidx.room.Database; import androidx.room.RoomDatabase; @Database(entities = {Student.class}, version = 1) public abstract class AppDatabase extends RoomDatabase { public abstract StudentDao studentDao(); } |
Step 5: Create a database object to use the database. The database object is created as an object derived from the database class and is given parameters such as context and database name required to use the database. For example, you can create a database object as follows:
1 2 3 |
AppDatabase db = Room.databaseBuilder(this, AppDatabase.class, "database-name").build(); |
From this point on, you can use the db.studentDao
() method for database operations. For example, to add a student, you can write the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Student student = new Student("John Doe", "johndoe@email.com"); Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { db.studentDao().insert(student); List<Student> students = db.studentDao().getAll(); for (Student s : students) { Log.d("Student", "Id: " + s.getId() + " Name: " + s.getName() + " Email: " + s.getEmail()); } } }); |
This code creates an instance of the Student
class with the name “John Doe” and email “johndoe@email.com”. Then, it uses an executor to execute a runnable task in a single thread.
In the runnable task, it inserts the student
instance into the database using the insert
method of the studentDao
object. Then, it retrieves a list of all students from the database using the getAll
method of the studentDao
object.
Finally, it iterates through the list of students and logs each student’s information including their id, name, and email using the Log.d
method. The log will contain the tag “Student” and the message “Id: [student id] Name: [student name] Email: [student email]”.
Android Room Annotation
This is a list of annotations that can be used with Android Room database classes to define and access the database.
Here’s a brief explanation of each annotation:
- @Entity: Used to define a data object that will be stored in the database.
- @PrimaryKey: Used to define the primary key of a data object.
- @ColumnInfo: Used to label a column of a data object.
- @Ignore: Used to specify a field of a data object that will not be serialized.
- @Dao: An interface used to perform read, add, update, and delete operations on the database data.
- @Query: Used to write SQL queries to query data from the database.
- @Insert: Used to insert data into the database.
- @Update: Used to update data in the database.
- @Delete: Used to delete data from the database.
- @Transaction: Used to ensure that database transactions are processed as a whole.