我想访问我的AnkoComponent
内部的ANKO SQLite数据库。但是,系统提示我在组件范围内出现错误,并且在使用AnkoComponent
的活动中,它工作正常。
这是我的ANKO SQLite数据库
package com.example.jokegenerator
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import org.jetbrains.anko.db.*
class DatabaseOpenHelper(context: Context) :
ManagedSQLiteOpenHelper(context, "Database", null, 2) {
companion object {
private var instance: DatabaseOpenHelper? = null
@Synchronized
fun getInstance(ctx: Context): DatabaseOpenHelper {
if (instance == null) {
instance = DatabaseOpenHelper(ctx.getApplicationContext())
}
return instance!!
}
}
override fun onCreate(db: SQLiteDatabase) {
// Here you create tables
db.createTable("Jokes", true,
"id" to INTEGER + PRIMARY_KEY + UNIQUE,
"joke" to TEXT)
db.insert("Jokes",
"joke" to "Humor is not for everyone")
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.dropTable("User", true)
}
}
val Context.database: DatabaseOpenHelper
get() = DatabaseOpenHelper.getInstance(getApplicationContext())
这是使用ANKO布局组件的活动,在该组件中,组件应使用按钮内的数据库。我已在AnkoComponent
的代码中添加了注释,以进行指定。
class JokeActivityUI : AnkoComponent<JokeActivity> {
override fun createView(ui: AnkoContext<JokeActivity>) = with(ui) {
verticalLayout {
textView {
}.lparams(width = matchParent) {
}
var getRndJoke = button {
text = "get random joke!"
onClick {
database.use{ //prompted with error written below!
}
}
}.lparams(width = matchParent) {
}
button {
text = "create a joke"
onClick {
startActivity<CreateJokeActivity>()
}
}.lparams(width = matchParent) {
}
button {
text = "frontpage"
onClick {
startActivity<MainActivity>()
}
}.lparams(width = matchParent) {
}
}
}
}
但是提示我的错误消息是:
公共val Context.database:在中定义的DatabaseOpenHelper 文件Database.kt中的com.example.jokegenerator
但是在使用布局的活动中,我可以很好地使用数据库
class JokeActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
JokeActivityUI().setContentView(this)
database.use { //works just fine in this scope
val dbJokes = database.use {
select("Jokes")
}
}
}
}
答案 0 :(得分:1)
为什么不从“活动”中访问它?我认为最好让UI只关注UI。
首先,在JokeActivityUI中创建名为getRndJoke的lateinit变量
class JokeActivityUI : AnkoComponent<JokeActivity> {
lateinit var getRndJoke: Button
...
}
然后将变量getRndJoke分配给按钮
getRndJoke = button {
text = "get random joke!"
}.lparams(width = matchParent)
因此,您可以像这样轻松地在Activity中访问数据库:
class JokeActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
JokeActivityUI().setContentView(this)
JokeActivityUI().getRndJoke.onClick {
database.use {
...
}
}
}
}
额外:我认为最好这样创建实例JokeActivityUI:
val ui = JokeActivityUI()