Android SQLite CursorIndexOutOfBounds

时间:2012-05-04 02:02:18

标签: java android sqlite

由于某些原因,当找不到我输入的用户名时,应用程序崩溃了。但是当找到用户名时,它似乎运行得很完美。我甚至检查一下返回的游标是否== null。继承人的代码

    public boolean isUserAuthenticated(String username, String password) {
    // TODO Auto-generated method stub
    boolean authenticated = false;
    String[] columns = new String[] {LOGIN_USERNAME, LOGIN_PASSWORD};
    String sqlUsername = "\"" + username + "\"";
    Cursor c = ourDatabase.query(LOGIN_TABLE, columns, LOGIN_USERNAME + "="+ sqlUsername, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
        String passwordAttachedToUsername = c.getString(1);
        if(passwordAttachedToUsername.equals(password)) {
            authenticated = true;
        }
    }

    return authenticated;
}

5 个答案:

答案 0 :(得分:3)

您的Cursor对象可能不为null,但其结果集的大小为0.而不是:

if (c != null) {
    ...
}

尝试:

if (c.getCount() > 0) {
    ...
}

另外,由于提到的@mu太短,你可以在条件中使用c.moveToFirst()的返回值:

if (c.moveToFirst()) {
    String passwordAttachedToUsername = c.getString(1);
    if (passwordAttachedToUsername.equals(password)) {
        authenticated = true;
    }
}

答案 1 :(得分:2)

首先,条件应该是:

if (c != null && c.getCount() > 0)

其次,你可以重构

String passwordAttachedToUsername = c.getString(1);
if(passwordAttachedToUsername.equals(password)) {
    authenticated = true;
    }

代之以:

authenticated = password.equals(c.getString(1));

答案 2 :(得分:1)

变化:

if (c != null) {
    c.moveToFirst();
    ...
}

if (c != null && c.moveToFirst()) {
    ...
}

如果c != null且光标大小大于0,则返回true。

答案 3 :(得分:0)

query命令将始终返回游标,因此对null的测试将始终失败。您需要使用cursor.getCount()

检查光标包含的计数

答案 4 :(得分:0)

if (cursor != null && cursor.getCount() > 0) {
if (c.moveToFirst()) {
          String passwordAttachedToUsername = c.getString(1);
          if(passwordAttachedToUsername.equals(password)) {
           authenticated = true;
    }}
                    // your logic goes here
                } else {
                    Toast.makeText(getApplicationContext(), "No Record Found", 1000).show();
                }