Room(SQLite) and Kotlin
Continuing with our project layout from this post, We’re going to change our data source to an SQLite DB.
To ease the way in which we do this, we’ll use Room. The Room persistence library provides an abstraction layer over SQLite.
To use Room in your app, add the following dependencies to your app’s build.gradle
file:
dependencies { ....
kapt "org.xerial:sqlite-jdbc:3.34.0"
// Room
def room_version = "2.3.0"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
kapt "androidx.room:room-compiler:$room_version"
implementation "androidx.room:room-ktx:$room_version"
}
Note: the “sqlite-jdbc” needed at the time of this blog if you’re running an arm processor as you’ll get this without it: “No native library is found for os.name=Mac and os.arch=aarch64”
After adding those dependencies, let’s once again continue with a clean architectured project by creating the following structure. We’ll only cover the files on display
├─Core
├─Presentation
├─Domain
│ ├─Model
│ │ └─ Todo.kt
│ └─Repository
│ └─ TodoRepository.kt
└─Data
├─DataSource
│ ├─ TodoDataSource.kt
│ └─Room
│ ├─ TodoDao.kt
│ ├─ TodoDatabase.kt
│ ├─ TodoRoomDataSourceImpl.kt
│ └─Entity
│ └─TodoRoomEntity.kt
└─Repository
└─TodoRepositoryImpl.kt
Let’s start with the Domain Layer. This describes WHAT our app is doing. So we’ll create a Todo Entity and TodoRepository
Next, we’ll specify what our Datasource must do by creating the TodoDataSource interface
Ok now let’s implement these project details:
We need three things to allow our Kotlin code to talk to our SQLite DB:
- Data entities: data classes that represent database tables
- Data access objects (DAO): container of methods that map to SQL queries
- Database class: the main access point for persisting data
Let’s start with our data entity. We’ll name this TodoRoomEntity as this represents a room-specific entity. Note how the extra mapping code from TodoRoomEntity to Todo data class in the Domain layer.
Now let’s create the DAO and the database
To use the Dao we can create a data source that conforms to the TodoDataSource. We inject the DAO as a dependency.
and then lastly, our TodoRepositoryImpl would implement our TodoRepository: