-1
代碼1是一個來自網頁的示例項目,我不知道代碼1中的override fun onCreate(db: SQLiteDatabase)
中的var db如何傳遞值。db如何在Kotlin中傳遞值?
我檢查了源代碼都ManagedSQLiteOpenHelper和SQLiteOpenHelper,我還不明白!
代碼1
class ForecastDbHelper(ctx: Context = App.instance) : ManagedSQLiteOpenHelper(ctx,
ForecastDbHelper.DB_NAME, null, ForecastDbHelper.DB_VERSION) {
companion object {
val DB_NAME = "forecast.db"
val DB_VERSION = 1
val instance by lazy { ForecastDbHelper() }
}
override fun onCreate(db: SQLiteDatabase) {
db.createTable(CityForecastTable.NAME, true,
CityForecastTable.ID to INTEGER + PRIMARY_KEY,
CityForecastTable.CITY to TEXT,
CityForecastTable.COUNTRY to TEXT)
db.createTable(DayForecastTable.NAME, true,
DayForecastTable.ID to INTEGER + PRIMARY_KEY + AUTOINCREMENT,
DayForecastTable.DATE to INTEGER,
DayForecastTable.DESCRIPTION to TEXT,
DayForecastTable.HIGH to INTEGER,
DayForecastTable.LOW to INTEGER,
DayForecastTable.ICON_URL to TEXT,
DayForecastTable.CITY_ID to INTEGER)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.dropTable(CityForecastTable.NAME, true)
db.dropTable(DayForecastTable.NAME, true)
onCreate(db)
}
}
ManagedSQLiteOpenHelper
abstract class ManagedSQLiteOpenHelper(
ctx: Context,
name: String,
factory: SQLiteDatabase.CursorFactory? = null,
version: Int = 1
): SQLiteOpenHelper(ctx, name, factory, version) {
private val counter = AtomicInteger()
private var db: SQLiteDatabase? = null
fun <T> use(f: SQLiteDatabase.() -> T): T {
try {
return openDatabase().f()
} finally {
closeDatabase()
}
}
@Synchronized
private fun openDatabase(): SQLiteDatabase {
if (counter.incrementAndGet() == 1) {
db = writableDatabase
}
return db!!
}
@Synchronized
private fun closeDatabase() {
if (counter.decrementAndGet() == 0) {
db?.close()
}
}
}
SQLiteOpenHelper
public abstract class SQLiteOpenHelper {
public SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version) {
throw new RuntimeException("Stub!");
}
public SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version, DatabaseErrorHandler errorHandler) {
throw new RuntimeException("Stub!");
}
public String getDatabaseName() {
throw new RuntimeException("Stub!");
}
public void setWriteAheadLoggingEnabled(boolean enabled) {
throw new RuntimeException("Stub!");
}
public SQLiteDatabase getWritableDatabase() {
throw new RuntimeException("Stub!");
}
public SQLiteDatabase getReadableDatabase() {
throw new RuntimeException("Stub!");
}
public synchronized void close() {
throw new RuntimeException("Stub!");
}
public void onConfigure(SQLiteDatabase db) {
throw new RuntimeException("Stub!");
}
public abstract void onCreate(SQLiteDatabase var1);
public abstract void onUpgrade(SQLiteDatabase var1, int var2, int var3);
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
throw new RuntimeException("Stub!");
}
public void onOpen(SQLiteDatabase db) {
throw new RuntimeException("Stub!");
}
}