Android room persistence library is a layer upon the SQLite database to give us the most robust access to the database. The room persistence library is also a part of Android Architecture Components. With the help of Room library, we have fluent database access while harnessing the full power of SQLite.
In this post, I will explain to you how we can create a Database using Room and perform CURD(Create, Read update and delete) operation on SQLite. I will cover all the basics of the Android room persistence library in this post so let’s begin.
Prerequisites
Before we start I hope you have basic knowledge of Database and Query and also Android Application development.
Implementation of Android Room persistence Library
Start creating a new Android project in Android. Once your project is ready you need to implement Room library in your project go to project
⇾ app
⇾ build.gradle
and add Room library
implementation "androidx.room:room-runtime:2.2.3" annotationProcessor "androidx.room:room-compiler:2.2.3"
Note: The reason why the annotation processor is needed is that all operations like Insert, Delete, Update, etc are annotated.
Once you add the above code sync your project to add this library in the project.
Creating an Entity class for Room
Now in this step, we will create an Entity class which is basically our Model (Getter / Setter) with @entity keyword. We will define our table column here and also define autoincrement etc. I create a package inside my main package and name it as a model and create an Entity class with name UserTable.
@Entity(tableName = "users") public class UserTable { @PrimaryKey(autoGenerate = true) int id; @ColumnInfo(name = "name") String name; 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 getStatus() { return status; } public void setStatus(String status) { this.status = status; } @ColumnInfo(name = "status") String status; }
This is my model class where I define table column (id, name, status) and also define auto-increment datatype.
Creating a DAO interface for Room
Now we need to create a DAO interface that acts as an intermediary between database and user. You can define all Query here which you want to run on your table.
@Dao public interface UserQueryDao { @Query("SELECT * FROM users") LiveData<List<UserTable>> fetchAllUsers(); @Query("SELECT * FROM users") List<UserTable> getAllUsersList(); @Insert Long insertTask(UserTable user); @Query("SELECT id, name, status FROM users WHERE id=:id") LiveData<UserTable> getUser(int id); @Query("DELETE FROM users WHERE id=:id") void deleteSpecific(int id); @Query("DELETE FROM users WHERE 1=1") void deleteAll(); @Update void updateUsers(UserTable userTable); }
Creating a Database class for Room
Here you can define your database name and its version
@Database(entities = {UserTable.class}, version = 1) public abstract class AppDatabase extends RoomDatabase { public abstract UserQueryDao queryDao(); }
Creatin action class to perform CURD on the table in Room
Now we create a class that communicates with the database and perform Actions like create read update delete operation on table. With this class, we can access database class and DAO to perform the operation shown in the below code.
public class UserActions { private String DB_NAME = "users"; private AppDatabase userDB; public UserActions(Context context) { userDB = Room.databaseBuilder(context, AppDatabase.class, DB_NAME).build(); } public LiveData<List<UserTable>> getLiveUsers() { return userDB.queryDao().fetchAllUsers(); } public List<UserTable> getAllUsers() throws ExecutionException, InterruptedException { return new getAllAsyncTask(userDB).execute().get(); } private static class getAllAsyncTask extends android.os.AsyncTask<Void, Void, List<UserTable>> { private AppDatabase userDB; List<UserTable> a; getAllAsyncTask(AppDatabase dao) { userDB = dao; } @Override protected List<UserTable> doInBackground(Void... voids) { return userDB.queryDao().getAllUsersList(); } } public void insertTask(String name, String status) { UserTable user = new UserTable(); user.setName(name); user.setStatus(status); insert(user); } public void insert(final UserTable user) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { userDB.queryDao().insertTask(user); return null; } }.execute(); } public void delete(final int id) { final LiveData<UserTable> user = getUser(id); if (user != null) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { userDB.queryDao().deleteSpecific(id); return null; } }.execute(); } } public void update(final UserTable userData) { final LiveData<UserTable> user = getUser(userData.getId()); if (user != null) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { userDB.queryDao().updateUsers(userData); return null; } }.execute(); } } public void deleteAll() { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { userDB.queryDao().deleteAll(); return null; } }.execute(); } public LiveData<UserTable> getUser(int id) { return userDB.queryDao().getUser(id); } }
In the above code, you will see that I am using AsyncTask to perform some operation is because If you run a query on the main thread your app will crash.
Sample to perform the basic operation using Android Room code
1. To perform Insert
operation run this code.
UserActions userActions = new UserActions(getApplicationContext()); userActions.insertTask("Aneh Thakur", "Welcome to trinitytuts");
2. To perform Update
operation run code like this
UserActions userActions = new UserActions(getApplicationContext()); UserTable user = userActions.getUser(1); user.setName(name.getText().toString()); user.setStatus(status.getText().toString()); userActions.update(user);
3. To perform View
operation run code like this
UserActions userActions = new UserActions(getApplicationContext());
userActions.getUser(id).observe((LifecycleOwner) act, new Observer<UserTable>() { @Override public void onChanged(UserTable userTable) { Toast.makeText(mContext, userTable.getId()+" "+userTable.getName()+" "+userTable.getStatus(), Toast.LENGTH_LONG).show(); } });
4. To perform Delete
operation run code like this
UserActions userActions = new UserActions(getApplicationContext()); userActions.delete(1);
5. Load all users from the database
UserActions userActions = new UserActions(getApplicationContext());
userActions.getLiveUsers().observe(MainActivity.this, new Observer<List<UserTable>>() { @Override public void onChanged(List<UserTable> userTables) { Log.e("length", userTables.size()+""); for(UserTable user : userTables) { Log.e(TAG, user.getId()); Log.e(TAG, user.getName()); } } });
6. If you want to load data in the list, not in live data you can call this method
UserActions userActions = new UserActions(getApplicationContext()); userActions.getAllUsers();
That’s It. I hope this post will help you to understand the Implementation of the Android Room library in your project you can download sample code from the below link.
Don’t forget to subscribe to our Youtube channel from the above link and share this post with your friends.
Thanks.
You can also read this post:- how to implement Google reCaptcha in Android