Day99 of #100DaysOfCode
2 min readMay 16, 2022
Hii folks 🙌
Today I will be continuing the same pathway in which we will learn about the databases.
Android Room
Room is a persistence library, part of the Android Architecture Components. It makes it easier to work with SQLiteDatabase objects in your app, decreasing the amount of boilerplate code and verifying SQL queries at compile time.
- In the project-level
build.gradle
file, we will define theroom_version
in the ext block.
ext {
kotlin_version = "1.3.72"
nav_version = "2.3.1"
room_version = '2.3.0'
}
- In the app-level
build.gradle
file, at the end of the dependencies list, we will add the following dependencies.
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"// optional - Kotlin Extensions and Coroutines support for Room
implementation "androidx.room:room-ktx:$room_version"
Then, we will Sync the changes and build the project to verify whether the dependencies were added correctly or not.
- Now we will create an Entity
@Entity
data class Schedule(
@PrimaryKey val id: Int,
@NonNull @ColumnInfo(name = "stop_name") val stopName: String,
@NonNull @ColumnInfo(name = "arrival_time") val arrivalTime: Int
)
- Then we will define a DAO
@Dao
interface ScheduleDao {
}
- Define a function
getAll()
that returns a List ofSchedule
objects including the@Query
annotation:
@Query("SELECT * FROM schedule ORDER BY arrival_time ASC")
fun getAll(): List<Schedule>
- We will define a
getByStopName()
function that takes aString
parameter calledstopName
and returns aList
ofSchedule
objects.
@Query("SELECT * FROM schedule WHERE stop_name = :stopName ORDER BY arrival_time ASC")
fun getByStopName(stopName: String): List<Schedule>
That is all for Day99 ✅
Thanks for reading, See you tomorrow!