在AsyncTask中使用kotlin初始化数据库 [英] Initialize database using kotlin in AsyncTask

查看:195
本文介绍了在AsyncTask中使用kotlin初始化数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的doInBackground我声明并初始化db时,出现错误,提示类型不匹配.我应该放什么而不是放this?

In my doInBackground I declare and Initialize db, I got an error which say type mismatch. What should I put instead of putting this?

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

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

What should I put, There say Required: Context!

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

And this is my async task code, That Problem at 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中初始化上下文.

Then in UpgradeDB, initialize the context.

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

最后

dbHelper = MyDBHelper(mContext)

这篇关于在AsyncTask中使用kotlin初始化数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆