将预先创建的SQLite数据库用于Kotlin中的Android项目

时间:2018-11-12 21:18:41

标签: android database sqlite

我正在尝试在我的Android应用中使用一个已经存在的sqLite数据库。我已经验证它已加载到资产文件夹中的项目中,并且当我直接从项目中打开它时,可以在数据库浏览器中对其进行浏览。

这是我要查询的表的模式

CREATE TABLE "ACTIVITY_LIST_TBL" ( 
`_ID` INTEGER NOT NULL, 
`ACT_NAME` VARCHAR NOT NULL, 
`ACT_CODE` VARCHAR, 
`IS_ACTIVE` INTEGER DEFAULT -1, 
PRIMARY KEY(`_ID`) )

以下是创建sqlite助手的活动,然后在按钮上单击“我在ACTIVITY_LIST_TBL上执行查询”。执行查询时,将引发此异常:

  

android.database.sqlite.SQLiteException:没有这样的表:ACTIVITY_LIST_TBL(代码1 SQLITE_ERROR):,而在编译时:SELECT * FROM ACTIVITY_LIST_TBL

class CalendarActivity : AppCompatActivity() {

private var cursor:Cursor? = null

override fun onCreate(savedInstanceState:Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.calendar_activity)

    findViewById<Button>(R.id.CalTestButton).setOnClickListener {

        val myDbHelper = DatabaseHelper(this)

        try { myDbHelper.createDataBase() }
        catch (ioE: IOException) { throw Error("Unable to create database") }

        try { myDbHelper.openDataBase() }
        catch (sqlE: SQLException) { throw sqlE }

        Toast.makeText(this, "Successfully Imported", Toast.LENGTH_SHORT).show()

        cursor = myDbHelper.query("ACTIVITY_LIST_TBL", null, null, null, null, null, null)

        cursor?.let {
            if (cursor!!.moveToFirst()) {
                do {
                    Toast.makeText(this,
                            "ACTIVITY_ID: " + cursor!!.getString(0) + "\n" +
                                    "ACTIVITY_NAME: " + cursor!!.getString(1) + "\n" +
                                    "ACTIVITY_CODE: " + cursor!!.getString(2) + "\n" +
                                    "IS_ACTIVE:  " + cursor!!.getString(3),
                            Toast.LENGTH_LONG).show()
                } while (cursor!!.moveToNext())
            }
        }
}

这是我的数据库帮助程序(我正在运行的实际查询可以在该文件的底部找到-我故意对表名进行硬编码以进行调试):

class DatabaseHelper(private val myContext: Context) : SQLiteOpenHelper(myContext, DB_NAME, null, DB_VERSION) {

private var DB_PATH: String? = null
private var calendarDatabase: SQLiteDatabase? = null


companion object {
    private val DB_NAME = "calendarDb"
    private val DB_VERSION = 1

}


init {
    this.DB_PATH = "/data/data/" + myContext.packageName + "/" + "databases/"
    Timber.e("Path 1: $DB_PATH")
}


@Throws(IOException::class)
fun createDataBase() {
    val dbExist = checkDataBase()
    if (dbExist) {
    } else {
        this.readableDatabase
        try {
            copyDataBase()
        } catch (e: IOException) {
            throw Error("Error copying database")
        }

    }
}

private fun checkDataBase(): Boolean {
    var checkDB: SQLiteDatabase? = null
    try {
        val myPath = DB_PATH!! + DB_NAME
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY)
    } catch (e: SQLiteException) {
    }

    checkDB?.close()
    return if (checkDB != null) true else false
}

@Throws(IOException::class)
private fun copyDataBase() {
    val myInput = myContext.assets.open(DB_NAME)
    val outFileName = DB_PATH!! + DB_NAME
    val myOutput = FileOutputStream(outFileName)
    val buffer = ByteArray(10)

    var length: Int = myInput.read(buffer)

    while (length  > 0) {
        myOutput.write(buffer, 0, length)
        length = myInput.read(buffer)
    }
    myOutput.flush()
    myOutput.close()
    myInput.close()

}

@Throws(SQLException::class)
fun openDataBase() {
    val myPath = DB_PATH!! + DB_NAME
    calendarDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY)

}

@Synchronized
override fun close() {
    if (calendarDatabase != null)
        calendarDatabase!!.close()
    super.close()
}


override fun onCreate(db: SQLiteDatabase) {}

override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
    if (newVersion > oldVersion)
        try {
            copyDataBase()
        } catch (e: IOException) {
            e.printStackTrace()

        }

}

fun query(table: String, columns: Array<String>?, selection: String?, selectionArgs: Array<String>?, groupBy: String?, having: String?, orderBy: String?): Cursor {

    return calendarDatabase!!.query("ACTIVITY_LIST_TBL", null, null, null, null, null, null)
}

}

似乎我必须以某种方式以错误的方式加载数据库,我们将不胜感激。

请注意,我已经通过在数据库浏览器中执行以下行来设置数据库与Android兼容:

  

创建表“ android_metadata”(“区域设置” TEXT DEFAULT'en_US')

     

插入“ android_metadata”值(“ en_US”)

我认为这无关紧要(我已经测试过了),但是我决定不将每个表的主键'_id'

0 个答案:

没有答案