So here's my database helper code
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)
}
here's the favorite data class
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"
}
}
but somehow i can't call my database instance from database helper anywhere, for example, i called it in my ScheduleDetailActity.kt, there is no database object
the goal is that this database can be called like this
database.use {
//Insert to database
}
Context.database should be defined outside the DatabaseHelper
scope. So your DatabaseHelper
should look like following
class DatabaseHelper(ctx: Context) : ManagedSQLiteOpenHelper(ctx, "FavoriteMatch.db", null, 1){
// Your previous code
}
val Context.database : DatabaseHelper
get() = getInstance(applicationContext)