Android SQLite:CursorIndex超出界限

时间:2014-12-05 03:42:13

标签: android sqlite

你好我得到一个OutOfBoundsExpection:请求索引0,大小为0.我的数据库之前正在工作。

以下是代码片段:

MainActivity.db = new DatabaseHandler(ncontext);
MainActivity.db.addPokemon(new Pokedex(0, "Bulbasaur", "001", "Grass/Poison", "Lv 5",1));

//Crashes:
Log.d(tag,"This is drawable: "+ MainActivity.db.getPokemon(0,1).getPokemonImage());

//DataBase class

        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_POKEMON, columns, KEY_ID + "=?" + " AND "
                + KEY_POKEMON_IMAGE + "=?", new String[] { String.valueOf(id),
                String.valueOf(poke_image) }, null, null, null, null);
        if ((cursor != null && cursor.moveToFirst()) ){
            cursor.moveToNext();
            cursor.close();
        }
        Log.d(Tag, "pre pokedex fetch");
        Pokedex pokemon;

        //CRASHES
        Log.d("Database","1: " + Integer.parseInt(cursor.getString(0)));
        // return pokemon
        pokemon = new Pokedex(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2), cursor.getString(3),
                cursor.getString(4), Integer.parseInt(cursor.getString(5)));
        Log.d(Tag, "getPokemon done");
        return pokemon;

知道出了什么问题吗?

1 个答案:

答案 0 :(得分:1)

您正在关闭光标并将光标移动到下一个位置而不处理if条件下的第一个结果集。更正下面的if条件

 if ((cursor != null && cursor.moveToFirst()) ){

        Log.d(Tag, "pre pokedex fetch");
        Pokedex pokemon;

        //CRASHES
        Log.d("Database","1: " + Integer.parseInt(cursor.getString(0)));
        // return pokemon
        pokemon = new Pokedex(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2), cursor.getString(3),
                cursor.getString(4), Integer.parseInt(cursor.getString(5)));
        Log.d(Tag, "getPokemon done");
        return pokemon;
        cursor.close();
 }