CursorIndexOutOfBoundsException:已请求索引21,大小为21

时间:2019-02-17 12:10:43

标签: java android indexoutofboundsexception

我尝试记录名称和年龄索引,并得到一个错误,提示它们超出范围,我不知道为什么。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SQLiteDatabase database = this.openOrCreateDatabase("Users"
            , MODE_PRIVATE, null);
    database.execSQL("CREATE TABLE IF NOT EXISTS users (name " +
            "VARCHAR, age INT(3))");
    database.execSQL("INSERT INTO users (name, age) VALUES ('Nick', 28)");
    database.execSQL("INSERT INTO users (name, age) VALUES ('Alon', 25)");

    Cursor cursor = database.rawQuery("SELECT * FROM users", null);

    int nameIndex = cursor.getColumnIndex("name");
    int ageIndex = cursor.getColumnIndex("age");

    cursor.moveToFirst();

    while (cursor != null && cursor.getCount() > 0){
        Log.i("name", cursor.getString(nameIndex));
        Log.i("age", cursor.getString(ageIndex));
        Toast.makeText(this, "hi", Toast.LENGTH_SHORT).show();
        cursor.moveToNext();
    }
}

}

我尝试在stackoverflow中寻找解决方案,但没有找到任何东西

标题中出现错误

1 个答案:

答案 0 :(得分:0)

尝试一下

:

您可以阅读this document来很好地添加sqlite。