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

问题描述 投票:0回答:1

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

@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中寻找解决方案,但没有找到任何东西

我得到了标题所说的错误

java android indexoutofboundsexception
1个回答
0
投票

试试这个

   if(cursor.moveToFirst()){
        do {
            String name = cursor.getString(nameIndex);
            String age = cursor.getString(ageIndex );

        }while (result.moveToNext());
    }

你可以阅读this document以便以一种好的方式添加sqlite。

© www.soinside.com 2019 - 2024. All rights reserved.