android.database.CursorIndexOutOfBoundsException:请求索引-1,大小为0

时间:2014-07-25 13:01:57

标签: android database android-sqlite

我在崩溃报告中收到此错误但无法弄清楚其含义。我认为是因为我说如果我的光标为空则返回-1。哪会导致崩溃。但我不确定为什么我的光标会为空?我的DB类中的这个方法在我的一个活动的onResume中被调用。在onCreate中调用它是否更好(这种方式只调用一次)?

public int getLastId() {
        String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_LEVEL, KEY_MONEY, KEY_DAYSLEFT, KEY_VOTES, KEY_CORRUPTION};
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns,null , null, null, null, null);

        if(c != null){
            c.moveToLast();
            int id = c.getInt(0);
            return id;
        }
        return -1;
    }

这段代码会更好吗?

public int getLastId() throws SQLException{
        String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_LEVEL, KEY_MONEY, KEY_DAYSLEFT, KEY_VOTES, KEY_CORRUPTION};
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns,null , null, null, null, null);

        if(c != null){
            c.moveToLast();
            int id = c.getInt(0);
            return id;
        }
        return 0;
    }

2 个答案:

答案 0 :(得分:1)

moveToLast()调用可能会引发这种情况,因为您的Cursor没有行,可能是因为您的表空了。

答案 1 :(得分:1)

好像你有一个空光标。因此也要检查光标count.i.e。改变

  if(c != null){
            c.moveToLast();
            int id = c.getInt(0);
            return id;
        }

 if(c != null && c.getCount() > 0){
            c.moveToLast();
            int id = c.getInt(0);
            return id;
        }
相关问题