android中的光标索引Out of Bounds Exception

时间:2017-03-23 02:54:48

标签: android database android-sqlite

在我的游戏中有一个得分板。没有得分仍然显示CursoreIndexOutOfBoundsException我想如何解决这个错误..有很多解决方案,但它对我来说不起作用下面是我的代码

public List<Rank> getRanking() {
    List<Rank> listRanking = new ArrayList<>();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c = db.rawQuery("SELECT * FROM Rank Order By Score DESC LIMIT 10;", null);
    try {

        if (c == null)
        {return null;}

        c.moveToNext();
        do {
            int Id = c.getInt(c.getColumnIndex("ID"));
            int Score = c.getInt(c.getColumnIndex("Score"));


            Rank ranking = new Rank(Id, Score);
            listRanking.add(ranking);
        } while (c.moveToNext());

    } catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        c.close();
        db.close();
    }
    return listRanking;

}

任何人都可以帮我解决这个问题。感谢任何帮助或建议。谢谢。

3 个答案:

答案 0 :(得分:1)

请尝试使用它,它将起作用: -

public List<Rank> getRanking() {
    List<Rank> listRanking = new ArrayList<>();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c = db.rawQuery("SELECT * FROM Rank Order By Score DESC LIMIT 10;", null);
    try {

        if (c == null)
        {return null;}

        while (c.moveToNext()) {
            int index = c.getColumnIndex("ID");
            int Id = 0;
            if (-1 != index) {
                Id = c.getInt(index);
            }
            index = c.getColumnIndex("Score");
            int Score = 0;
            if (-1 != index) {
                Score = c.getInt(index1);
            }


            Rank ranking = new Rank(Id, Score);
            listRanking.add(ranking);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        if (null != c) {
            c.close();
        }
        db.close();
    }
    return listRanking;

}

答案 1 :(得分:0)

尝试将第一个c.moveToNext()更改为c.moveToFirst():

unchecked

答案 2 :(得分:0)

问题在于,当没有下一个时,你将转向下一个。您需要检查并确保有下一个要去的地方。另外,摆脱第一个c.moveToNext()。你不需要它。它会让你跳过第一个值。只是做:

       try {

        if (c == null){
             return null;
        }
        do {
            int Id = c.getInt(c.getColumnIndex("ID"));
            int Score = c.getInt(c.getColumnIndex("Score"));


            Rank ranking = new Rank(Id, Score);
            listRanking.add(ranking);
            if(c.moveToNext() == null){
                 break;
             }
        } while (c.moveToNext());