gpt4 book ai didi

android - 在 AsyncTask 中使用 kotlin 初始化数据库

转载 作者:行者123 更新时间:2023-11-30 05:12:38 25 4
gpt4 key购买 nike

在我的 doInBackground 中,我声明并初始化了 db,我收到一个错误,提示类型不匹配。我应该放什么而不是放 this

var dbHelper: MyDBHelper? = null
dbHelper = MyDBHelper(this)

我应该放什么,那里说 Required: Context!

这是我的异步任务代码,dbHelper = MyDBHelper(this) 的问题。

private class UpgradeDB(textView: TextView?) : AsyncTask<String, String, String>() {
var innerTextView: TextView? = textView

override fun onPreExecute() {
innerTextView!!.visibility = View.VISIBLE
}

override fun doInBackground(vararg params: String): String? {
val filename = "eBOSSInv_Upgrade.sql"
val sdcard = Environment.getExternalStorageDirectory()
val file = File(sdcard, filename)

if (!file.exists()) isCancelled

try {
var dbHelper: MyDBHelper? = null

dbHelper = MyDBHelper(this)

dbHelper!!.writableDatabase.use { db ->
var intTotalLine = 0
var intLine = 1
BufferedReader(FileReader(file)).useLines { _ -> intTotalLine++ }
BufferedReader(FileReader(file)).use { r ->
r.lineSequence().forEach {
if (it.isNotEmpty()) {
db!!.execSQL(it)
publishProgress(String.format("Updating %s/%s records", intLine, intTotalLine))
intLine++
}
}
}
}
} catch (e: Exception) {

}
return null
}

override fun onProgressUpdate(vararg text: String) {
innerTextView!!.text = text[0]
}

override fun onPostExecute(result: String?) {
innerTextView!!.text = ""
}

override fun onCancelled() {

}
}

最佳答案

您需要将 context 传递给 Async Task

例子:

llUpdate.setOnClickListener { 
UpgradeDB(txtUpdate!!, getApplication()).execute("", "", "")
}

然后在UpgradeDB中,初始化上下文。

private class UpgradeDB(textView: TextView?, context: Context) : AsyncTask<String, String, String>() {
var innerTextView: TextView? = textView
var mContext:Context? = context // initialize context
}

最后

dbHelper = MyDBHelper(mContext)

关于android - 在 AsyncTask 中使用 kotlin 初始化数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53476189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com