Ankit Gusain Ankit Gusain -4 years ago 165
Android Question

Cursor Index Out Of Bounds Exception in android

There is a score Board in My game..There is no score still it shows CursoreIndexOutOfBoundsException how am i suppose to solve this error..there are many solution but it didnt work for me below is my code

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;

}


Can anyone help me with a solution to this problem.Any help or suggestion is appreciated.Thank you.

Answer Source

Please try with this it will work:-

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;

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download