A large application always consists of some kinds of a database to keep a store of large chunks of data that it receives from the server. One such database is the Realm Database.
While working on SUSI.AI app (a smart assistant open-source app) I found the necessity to store room name in the database. These room names were used while configuring SUSI Smart Speaker using the app. Let me share how I implemented this in the app.
Before we proceed with the implementation, let’s go through the prerequisites for using Realm with Android:
- Android Studio version 1.5.1 or higher
- JDK version 7.0 or higher
- A recent version of the Android SDK
- Android API Level 9 or higher (Android 2.3 and above)
First of all, you need to add the Gradle dependency at the app level.
Since we are going to do it in Kotlin, we need to add the following:
Since this is a database that is used throughout the application, we have to initialize the realm in the class that extends the Application class.
Once the realm is initialized, we set up a data model class. This model class contains the format of data to be stored. The model class should extend the RealmObject class. Also, the model class must use the keyword open. This makes it available for inheritance and allows it to be overridden. If we remove the open keyword here, we get an error stating: cannot inherit from the final model class.
When the realm objects are initialized at the start, the default values of the variables are declared null (Concept of Function Default Arguments in Kotlin).
Now to manipulate the database from the required files we need to create a reference to the Realm followed by getting the default instance of Realm.
To commit any operation with the database, the code must be written within beginTransaction and commitTransaction blocks. Below is an example where the room name is added to the database by using the model class mentioned above.
We use the above method to add data to the database. Now, if we can add data, we should be able to retrieve them too. Let’s go through the code snippet to retrieve data from the database.
The above snippet shows a function which extracts data from the database and stores them in an array list for displaying in a recycler view.
Now, we all went through addition, display of data in the realm database. Is that sufficient?? No, if we can add data to the database, then there also should be a way to delete the data when needed. Clearing/removing data all at once from the database is very easy and can be simply done by :
Reference: Realm Database