Kotlin数据库错误CursorIndexOutOfBoundsException

时间:2017-08-20 17:11:24

标签: java android sql sqlite kotlin

这是错误,它说索引越界,但我怎么能解决它,有一些土耳其语,但它们并不重要,我想:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.burhanozen.nothesaplama, PID: 26919
java.lang.RuntimeException: Unable to start activity 
ComponentInfo{com.example.burhanozen.nothesaplama/com.example.burhanozen.nothesaplama.MainActivity}: android.database.CursorIndexOutOfBoundsException: Index 1 requested, with a size of 1
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at ........

我试图存储某种学生信息。我有这些错误,我在下面分享代码。 这是我的MainActivity:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val toolbar = findViewById(R.id.toolbar) as Toolbar
    setSupportActionBar(toolbar)
    val fab = findViewById(R.id.fab) as FloatingActionButton
    fab.setOnClickListener {
        val intent = Intent(this@MainActivity,NotEkrani::class.java)
        startActivity(intent) }


    val studentsArray = ArrayList<String>()

    val arrayAdapter = ArrayAdapter(this,android.R.layout.simple_list_item_1,studentsArray)
    listView.adapter= arrayAdapter

    try{

        val myDatabase = this.openOrCreateDatabase("student", Context.MODE_PRIVATE,null)
        myDatabase.execSQL("CREATE TABLE IF NOT EXISTS students (isim TEXT," +
                " dersbir TEXT, dersbirkredi TEXT, dersbirort TEXT," +
                " dersiki TEXT, dersikikredi TEXT, dersikiort TEXT) ")

        val cursor = myDatabase.rawQuery("select * from students",null)

        val nameIx = cursor.getColumnIndex("isim")
        val dersbirIx = cursor.getColumnIndex("dersbir")
        val dersbirkrediIx = cursor.getColumnIndex("dersbirkredi")
        val dersbirortIx = cursor.getColumnIndex("dersbirort")
        val dersikiIx = cursor.getColumnIndex("dersiki")
        val dersikikrediIx = cursor.getColumnIndex("dersikikredi")
        val dersikiortIx = cursor.getColumnIndex("dersikiort")

        cursor.moveToNext()

        while (cursor != null){

            studentsArray.add(cursor.getString(nameIx))
            studentsArray.add(cursor.getString(dersbirIx))
            studentsArray.add(cursor.getString(dersbirkrediIx))
            studentsArray.add(cursor.getString(dersbirortIx))
            studentsArray.add(cursor.getString(dersikiIx))
            studentsArray.add(cursor.getString(dersikikrediIx))
            studentsArray.add(cursor.getString(dersikiortIx))

            cursor.moveToNext()

            arrayAdapter.notifyDataSetChanged()


        }
        while (cursor!=null){
            cursor!!.close()
        }



    }catch (e:SQLException){

    }

这是我的第二个活动页面,我在这里没有任何错误,但可能会有所帮助。我在这里写了数据库代码。

fun kaydet(view:View){
    val isim = isim.text.toString()
    val dersbir = dersbir.text.toString()
    val dersbirkredi = dersbirkredi.text.toString()
    val dersbirort = dersbirort.text.toString()
    val dersiki = dersiki.text.toString()
    val dersikikredi = dersikikredi.text.toString()
    val dersikiort = dersikiort.text.toString()

    try {
        val myDatabase = openOrCreateDatabase("student", Context.MODE_PRIVATE,null)

        myDatabase.execSQL("CREATE TABLE IF NOT EXISTS students (isim TEXT," +
                " dersbir TEXT, dersbirkredi TEXT, dersbirort TEXT," +
                " dersiki TEXT, dersikikredi TEXT, dersikiort TEXT) ")

        val sqlString = "INSERT INTO students (isim,dersbir,dersbirkredi,dersbirort,dersiki,dersikikredi,dersikiort) VALUES(?,?,?,?,?,?,?)"
        val statement = myDatabase.compileStatement(sqlString)

        statement.bindString(1,isim)
        statement.bindString(2,dersbir)
        statement.bindString(3,dersbirkredi)
        statement.bindString(4,dersbirort)
        statement.bindString(5,dersiki)
        statement.bindString(6,dersikikredi)
        statement.bindString(7,dersikiort)
        statement.execute()


    }catch (e:SQLException){

    }
    val intent = Intent(this,MainActivity::class.java)
    startActivity(intent)

}

2 个答案:

答案 0 :(得分:1)

将while循环更改为如下所示:

    while (cursor.moveToNext()){

        studentsArray.add(cursor.getString(nameIx))
        ...


    }

(从代码中删除所有其他cursor.moveToNext()

您正在检查while循环条件中的cursor != null,但在从光标读取所有行后它不会变为null。

在上面的代码中,如果下一行有cursor.moveToNext,则返回true。否则返回false并且循环终止。

而且,只是注意到,你应该改变它,

while (cursor!=null){
      cursor!!.close()
}

到if检查:

if (cursor!=null){
      cursor.close()
}

或者,正如注释中建议的Todd,您可以使用高阶函数use自动关闭游标,这与Java 7 try-with-resources类似。

cursor.use {
    while (cursor.moveToNext()){

            studentsArray.add(cursor.getString(nameIx))
            ...


    }
}

答案 1 :(得分:1)

您收到此错误是因为光标大小为1.数据库中只有一条记录。但是你要查询数据库超过1次。这就是你错误的原因。

首先,您的完整执行代码是错误的。

您正在活动中创建数据库。如果这样做,就无法正确有效地管理数据库。

首先,您必须在单独的类中创建SqliteOpenHelper数据库。然后你必须在那里创建一个表。然后在那里编写辅助方法以从中获取和插入值。

您的数据库类应如下例所示。

class DbHelper(context: Context) : SQLiteOpenHelper(context, "example.db", null, 4) {
    val TAG = javaClass<DbHelper>().getSimpleName()
    val TABLE = "logs"

    companion object {
        public val ID: String = "_id"
        public val TIMESTAMP: String = "TIMESTAMP"
        public val TEXT: String = "TEXT"
    }

    val DATABASE_CREATE =
        "CREATE TABLE if not exists " + TABLE + " (" +
        "${ID} integer PRIMARY KEY autoincrement," +
        "${TIMESTAMP} integer," +
        "${TEXT} text"+
        ")"

    fun log(text: String) {
        val values = ContentValues()
        values.put(TEXT, text)
        values.put(TIMESTAMP, System.currentTimeMillis())
        getWritableDatabase().insert(TABLE, null, values);
    }

    fun getLogs() : Cursor {
        return getReadableDatabase()
                .query(TABLE, arrayOf(ID, TIMESTAMP, TEXT), null, null, null, null, null);
    }

    override fun onCreate(db: SQLiteDatabase) {
        Log.d(TAG, "Creating: " + DATABASE_CREATE);
        db.execSQL(DATABASE_CREATE)
    }

    override fun onUpgrade(p0: SQLiteDatabase, p1: Int, p2: Int) {
    }

}

由于您使用Kotin数据库非常容易使用 Anko-Sqlite 。通过这个库,从数据库中存储和检索数据非常容易。你可以在这里查看。 https://github.com/Kotlin/anko/wiki/Anko-SQLite#using-anko-sqlite-in-your-project