Read complete story

Android Basic Structure – Kotlin and Room Database android

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:

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.

  1. Entity:- A Java or a Kotlin class which represents a table within the database.
  2. 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.
  3. 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.

Android Room Persistence Library

 

How to implement?

Step 1: First of all, Create a Model class means a column for our database, add an Entity class

Step 2: Now, we need a DAO (Data Access Object), which will be used for accessing the database.

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,

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.

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. 🙂

. . .

Comment

Add Your Comment

Be the first to comment.

css.php
Hire Us!
Brief us about your requirements and we'll get back to you.
Woo! Hooy!
We have just recieved your project brief and our expert will contact you shortly.
Send Again
Close