Android SQLite游标索引越界问题

3

由于某些原因,当我输入的用户名未找到时,应用程序会崩溃。但是当找到该用户名时,它似乎运行良好。我甚至进行了一个检查,看返回的游标是否为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个回答

3

您的游标对象可能不为空,但其结果集的大小为0。请改为:

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

尝试:

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

此外,正如 @mu is too short 所提到的,您可以在条件语句中直接使用 c.moveToFirst() 的返回值:
if (c.moveToFirst()) {
    String passwordAttachedToUsername = c.getString(1);
    if (passwordAttachedToUsername.equals(password)) {
        authenticated = true;
    }
}

2
或者您可以检查 moveToFirst 的返回值:http://developer.android.com/reference/android/database/Cursor.html#moveToFirst%28%29 - mu is too short
真的。那比我的解决方案更干净。 - anon

2

首先,条件应该是:

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

第二步,您可以进行重构。
String passwordAttachedToUsername = c.getString(1);
if(passwordAttachedToUsername.equals(password)) {
    authenticated = true;
    }

使用这个代替:

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

1

更改:

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

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

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


0

query 命令总是会返回一个游标,因此你的空值测试总是会失败。你需要使用 cursor.getCount() 检查游标包含的数量。


你的意思不是:你对 null 的测试总是会通过吗? - W.K.S

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();
                }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接