sqlite异常-cursorindexoutofboundsexception

f45qwnt8  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(390)

这个问题在这里已经有答案了

android.database.cursorindexoutofboundsexception:请求索引0,大小为0(7个答案)
上个月关门了。
我收到异常-android.database.cursorindexoutofboundsexception:请求索引0,大小为0
主要活动代码-

Cursor cursor  = db.rawQuery("Select * from Vocabwords", null);
cursor.moveToFirst();
String word = cursor.getString(1);
String meaning = cursor.getString(2);
TextView tv1 = findViewById(R.id.tv1);
TextView tv2 = findViewById(R.id.tv2);
tv1.setText(word);
tv2.setText(meaning);
cursor.close();
db.close();

sqlitehelper代码:

public void onCreate(SQLiteDatabase db) {   
    db.execSQL("create table Vocabwords (_id integer primary key autoincrement, Word text, Meaning text)");
    insertNewEntry(db, "Diabolic","Evil");
    insertNewEntry(db,"Concede","Agree to an argument after declaring it incorrect in past");
}

public void insertNewEntry( SQLiteDatabase db,String word, String meaning){
    ContentValues contentValues = new ContentValues();
    contentValues.put("Word", word);
    contentValues.put("Meaning", meaning);
    db.insert("Vocabwords", null, contentValues);
}
kx1ctssn

kx1ctssn1#

似乎表是空的,您正在尝试获取第一行的列值。
这就是为什么你应该首先检查方法 moveToFirst() 如果光标返回任何行:

Cursor cursor  = db.rawQuery("Select * from Vocabwords", null);

if (cursor.moveToFirst()) {
    String word = cursor.getString(1);
    String meaning = cursor.getString(2);
    TextView tv1 = findViewById(R.id.tv1);
    TextView tv2 = findViewById(R.id.tv2);
    tv1.setText(word);
    tv2.setText(meaning);
}

cursor.close();
db.close();

相关问题