1 year ago

#316220

test-img

pox

Pre-populating Room using Koin and DB Browser

I need to pre-populate a table in Room using a .csv file. I saw in https://developer.android.com/training/data-storage/room/prepopulate that I needed a .db file instead so I used DB Browser to import my .csv and create a .db file. I added my .db file to folder /assets and created an abstract class for my database, a dao and a data class, then added it in Koin using .createFromAsset. It's not creating anything though (I am checking in App Inspection). Not throwing any errors. Nothing. The .csv has around 20k entries.

This is my abstract class

@Database(entities = [PlantInfo::class], version = 1)
abstract class PlantInfoDB: RoomDatabase(){
    abstract fun plantInfoDao(): PlantInfoDao
}

This is my DAO


@Dao
interface PlantInfoDao {
    @Query("SELECT * FROM PlantInfo")
    fun getAllPlantInfo(): List<PlantInfo>
}

This is my Data Class

@Parcelize
@Entity(tableName = "PlantInfo")
data class PlantInfo(
    @PrimaryKey val id: Int,
    @ColumnInfo(name = "scientificName") val scientificName: String,
    @ColumnInfo(name = "commonName") val commonName: String,
    @ColumnInfo(name = "family") val family: String,
    @ColumnInfo(name = "description") val description: String,
    @ColumnInfo(name = "cultivation") val cultivation: String,
    @ColumnInfo(name = "light") val light: Int,
    @ColumnInfo(name = "water") val water: Int,
    @ColumnInfo(name = "disease") val disease: String,
    @ColumnInfo(name = "img") val img: String
) : Parcelable

My KoinGraph

object KoinGraph {

    val mainModule = module {

        single {
            Room.databaseBuilder(get(), PlantInfoDB::class.java, "PlantInfo")
            .createFromAsset("plants_db.db")
            .build()
        }

      single {
            Room.databaseBuilder(get(), AppDB::class.java, "AppDB")
                .build()
        }

        single { get<AppDB>().waterDao() }
        single { get<AppDB>().plantDao() }
        single { get<PlantInfoDB>().plantInfoDao() }
        factory { WaterAlarm(get()) }
        single { WaterRepository() }
        single { PlantIdRepository() }
        single { RandomQuotesRepository() }
        viewModel { SearchByPictureViewModel(get()) }
        viewModel { AddPlantPictureViewModel() }
        viewModel { HomePlantViewModel(get(), get()) }
        viewModel { PlantFormViewModel(get()) }
    }
}

This is my DB Browser file structure

CREATE TABLE "PlantInfo" (
    "id"    INTEGER NOT NULL UNIQUE,
    "scientificName"    TEXT,
    "commonName"    TEXT,
    "family"    TEXT,
    "description"   TEXT,
    "cultivation"   TEXT,
    "light" INTEGER,
    "water" INTEGER,
    "disease"   TEXT,
    "img"   TEXT,
    PRIMARY KEY("id")
)

enter image description here

Any help appreciated.

android

kotlin

android-room

android-database

koin

0 Answers

Your Answer

Accepted video resources