Hey, in this blog we will see how to use room database with Kotlin programming language.
I have worked on room database for past 3-4 months. Now I have switched to Kotlin instead of java for few weeks. It is really cool.
Why switch to Kotlin
Kotlin is a great fit for developing Android applications, bringing all of the advantages of a modern language to the Android platform without introducing any new restrictions:
- Interoperability: That is the first thing I like about Kotlin. You can call Java code from Kotlin and vice-versa seamlessly. Both Kotlin and Java generate the same bytecode, so there’s no issue that you’re shipping something completely different with Kotlin.
- Compatibility: Kotlin is fully compatible with JDK 6, ensuring that Kotlin applications can run on older Android devices with no issues.
- Performance: A Kotlin application runs as fast as an equivalent Java one, thanks to very similar bytecode structure. With Kotlin’s support for inline functions, code using lambdas often runs even faster than the same code written in Java.
- The == operator does what you actually expect.
- Would you like fast and convenient async programming? Of course, you would.
- No more NullPointerExceptions: Our team has been developing the Android application for three years, and NPE’s have been one of the most common reasons for crashes in our apps.
- And a lot more reason to switch to kotlin.
What is Room
The Room persistence library provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.
Before, getting into the implementation part, let’s understand the basic components of Room.
There are basically 3 major components in Room.
- Entity:- A Java or a Kotlin class which represents a table within the database.
- DAO:- DAO stands for DATA ACCESS OBJECT. This is basically an interface, which contains the methods like getData() or storeData() etc. which are used for accessing the database. This interface will be implemented by the Room.
- Database:- This is an abstract class that extends RoomDatabase, this is where you define the entities (tables)and the version number of your database. It contains the database holder and serves as the main access point for the underlying connection. And also manage the migration technique.
For more details please read this.
How to implement?
Step 1: First of all, Create a Model class means a column for our database, add an Entity class
1234567891011121314151617181920212223242526272829303132333435363738394041424344 @Entity(tableName = "administrator")class Administrator {@PrimaryKey(autoGenerate = true)var uid: Int = 0@ColumnInfo(name = "email")private var email: String = ""@ColumnInfo(name = "password")private var password: String = ""@Ignoreprivate var newPassword: String = ""@Bindablefun getEmail(): String {if (email == null)return ""return email}fun setEmail(email: String) {this.email = email}@Bindablefun getPassword(): String {if (password == null)return ""return password}fun setPassword(password: String) {this.password = password}@Bindablefun getNewPassword(): String {if (newPassword == null)return ""return newPassword}fun setNewPassword(newPassword: String) {this.newPassword = newPassword}}
Step 2: Now, we need a DAO (Data Access Object), which will be used for accessing the database.
1234567891011121314 @Daopublic interface AdministratorDao {@Query("SELECT * FROM Administrator")Administrator getAll();@Query("SELECT * FROM Administrator WHERE uid IN (:AdministratorIds)")List<Administrator> loadAllByIds(int[] AdministratorIds);@Insertvoid insertAll(Administrator... Administrators);@Deletevoid delete(Administrator Administrator);}
Step 3: Finally, we need a DatabaseClass, annotated with Database. The Database class establishes a logical grouping between the DAO interfaces. It also defines the required version number, which is used to track and implement database migrations,
123456789101112131415161718 @Database(entities = arrayOf(Administrator::class), version = 1)abstract class AppDataBase : RoomDatabase() {companion object {private var mINSTANCE: AppDataBase? = nullpublic fun getAppDatabase(context: Context): AppDataBase {if (mINSTANCE == null) {mINSTANCE = Room.databaseBuilder(context.getApplicationContext(), AppDataBase::class.java, DB_NAME).build()}return mINSTANCE as AppDataBase}fun destroyDbInstance() {mINSTANCE = null}}}
If you try running the above code with the created database above, your app will crash as the operation performed is on the main thread. By default, Room keeps a check of that and doesn’t allow operations on the main thread as it can make your UI laggy.
If you want to run your database query you have to add allowMainThreadQueries() in your database builder.
123 mINSTANCE = Room.databaseBuilder(context.getApplicationContext(), AppDataBase::class.java, DB_NAME).allowMainThreadQueries().build()
Now you have learned how to use Room database with kotlin. May be this blog is helpfull to you.
If you have any query please ask me on commet. Stay cool and stay updated. 🙂