1 Anko 异步
async() {
Request(url).run()
uiThread { longToast("Request performed") }
}
2 单例
1--------------
class App : Application() {
companion object {
private var instance: Application? = null
fun instance() = instance!!
}
override fun onCreate() {
super.onCreate()
instance = this
}
}
2------------
class App : Application() {
companion object {
var instance: App by Delegates.notNull()
}
override fun onCreate() {
super.onCreate()
instance = this
}
}
3 lazy 数据库
class App : Application() {
val database: SQLiteOpenHelper by lazy {
MyDatabaseHelper(applicationContext)
}
override fun onCreate() {
super.onCreate()
val db = database.writableDatabase
}
}
4 ManagedSqliteOpenHelper
public fun <T> use(f: SQLiteDatabase.() -> T): T {
try {
return openDatabase().f()
} finally {
closeDatabase()
}
}
val result = forecastDbHelper.use {
val queriedObject = ...
queriedObject
}
use 接收一个 SQLiteDatabase 的扩展函数。这表示,我们可以使
用 this 在大括号中,并且处于 SQLiteDatabase 对象中。
定义表
object CityForecastTable {
val NAME = "CityForecast"
val ID = "_id"
val CITY = "city"
val COUNTRY = "country"
}
object DayForecastTable {
val NAME = "DayForecast"
val ID = "_id"
val DATE = "date"
val DESCRIPTION = "description"
val HIGH = "high"
val LOW = "low"
val ICON_URL = "iconUrl"
val CITY_ID = "cityId"
}
继承ManagedSQLiteOpenHelper
class ForecastDbHelper() : ManagedSQLiteOpenHelper(App.instance,
ForecastDbHelper.DB_NAME, null, ForecastDbHelper.DB_VERS
ION) {
...
}
companion object {
val DB_NAME = "forecast.db"
val DB_VERSION = 1
val instance: ForecastDbHelper by lazy { ForecastDbHelper()
}