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 the room_version in the ext block.
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 of Schedule 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 a String parameter called stopName and returns a List of Schedule objects.
@Query("SELECT * FROM schedule WHERE stop_name = :stopName ORDER BY arrival_time ASC") fun getByStopName(stopName: String): List<Schedule>