我的anko-sqlite数据库对象无法调用

时间:2019-11-10 06:04:31

标签: android kotlin anko

这是我的数据库帮助程序代码

class DatabaseHelper(ctx: Context) : ManagedSQLiteOpenHelper(ctx, "FavoriteMatch.db", null, 1){

    companion object {
        private var instance: DatabaseHelper? = null

        @Synchronized
        fun getInstance(ctx: Context): DatabaseHelper {
            return instance ?: DatabaseHelper(ctx.applicationContext)
        }
    }

    override fun onCreate(db: SQLiteDatabase) {
        db.createTable(Favorite.TABLE_FAVORITE, true,
            Favorite.MATCH_ID to TEXT + PRIMARY_KEY,
            Favorite.TEAM_HOME_NAME to TEXT,
            Favorite.TEAM_HOME_GOAL to INTEGER,
            Favorite.TEAM_AWAY_NAME to TEXT,
            Favorite.TEAM_AWAY_GOAL to INTEGER,
            Favorite.EVENT_DATE to TEXT,
            Favorite.EVENT_TIME to TEXT)
    }

    override fun onUpgrade(db: SQLiteDatabase, p1: Int, p2: Int) {
        db.dropTable(Favorite.TABLE_FAVORITE, true)
    }

    val Context.database : DatabaseHelper
        get() = getInstance(applicationContext)
}

这是最喜欢的数据类

data class Favorite(
    val idEvent: String?,
    val strHomeTeam: String?,
    val strAwayTeam: String?,
    val strHomeGoalDetails: String?,
    val strAwayGoalDetails: String?,
    val dateEvent: String?,
    val strTime: String?
) {
    companion object {
        const val TABLE_FAVORITE: String = "TABLE_FAVORITE"
        const val MATCH_ID: String = "ID_"
        const val TEAM_HOME_NAME: String = "HOME_NAME"
        const val TEAM_HOME_GOAL: String = "HOME_GOAL"
        const val TEAM_AWAY_NAME: String = "AWAY_NAME"
        const val TEAM_AWAY_GOAL: String = "AWAY GOAL"
        const val EVENT_DATE: String = "DATE_EVENT"
        const val EVENT_TIME: String = "EVENT_TIME"
    }
}

但是以某种方式我无法从任何地方的数据库助手中调用数据库实例,例如,我在ScheduleDetailActity.kt中调用了它,没有数据库对象 enter image description here

目标是可以像这样调用该数据库

database.use {
   //Insert to database
}

1 个答案:

答案 0 :(得分:1)

Context.database应该在DatabaseHelper范围之外定义。因此,您的DatabaseHelper应该看起来像

 class DatabaseHelper(ctx: Context) : ManagedSQLiteOpenHelper(ctx, "FavoriteMatch.db", null, 1){

   // Your previous code 

}

val Context.database : DatabaseHelper
    get() = getInstance(applicationContext)