Create a Database

Kotlin and Android Development featuring Jetpack — by Michael Fazio (78 / 125)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Chapter 10 Load and Save Data with Coroutines and Room | TOC | Work with Retrofit 👉

The first part of the process here is going to be very familiar if you’ve gone through Chapter 5, Persist Game Data with Room, so I’ll try to speed through things to get to the new stuff.

Before you do anything, add in the Room dependencies:

»implementation ​"androidx.room:room-ktx:$room_version"​
»implementation ​"androidx.room:room-runtime:$room_version"​
​ implementation ​"com.google.android.material:material:$material_version"​

»kapt ​"androidx.room:room-compiler:$room_version"​

Then, inside a new data package, create an abstract BaseballDatabase class that inherits from RoomDatabase. It’ll start out pretty empty, but we’ll go through and add pieces in as we go along. For now, it looks like this:

​ @Database(
​ entities = [],
​ exportSchema = ​false​,
​ version = 1
​ )
​ ​abstract​ ​class​ BaseballDatabase : RoomDatabase() {
​ ​companion​ ​object​ {
​ @Volatile
​ ​private​ ​var​ Instance: BaseballDatabase? = ​null​

​ ​fun​ ​getDatabase​(context: Context, scope: CoroutineScope):
​ BaseballDatabase = Instance ?: synchronized(​this​) {
​ ​val​ instance = Room.databaseBuilder(
​ context,
​ BaseballDatabase::​class​.java,
​ ​"BaseballDatabase"​
​ ).build()
​…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.