Android的SQLite的CursorIndexOutOfBoundsAndroid、SQLite、CursorIndexOutOfBounds

由网友(你列表最软的妹)分享简介:出于某种原因,在未找到用户名I输入,应用程序崩溃。但是,当用户名发现它似乎完美运行。我甚至做了检查,如果返回的指针== null来看看。继承人的code 公共布尔isUserAuthenticated(字符串用户名,字符串密码){// TODO自动生成方法存根布尔认证= FALSE;的String []列=新的Stri...

出于某种原因,在未找到用户名I输入,应用程序崩溃。但是,当用户名发现它似乎完美运行。我甚至做了检查,如果返回的指针== null来看看。继承人的code

 公共布尔isUserAuthenticated(字符串用户名,字符串密码){
    // TODO自动生成方法存根
    布尔认证= FALSE;
    的String []列=新的String [] {LOGIN_USERNAME,LOGIN_PASSWORD};
    字符串sqlUsername =+用户名+;
    光标C = ourDatabase.query(LOGIN_TABLE,列,LOGIN_USERNAME +=+ sqlUsername,NULL,NULL,NULL,NULL);
    如果(C!= NULL){
        c.moveToFirst();
        串passwordAttachedToUsername = c.getString(1);
        如果(passwordAttachedToUsername.equals(密码)){
            认证= TRUE;
        }
    }

    返回认证;
}
 

解决方案

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

 如果(C!= NULL){
    ...
}
 
在Android中查看和管理sqlite数据库

尝试:

 如果(c.getCount()0){
    ...
}
 

此外,作为@mu太短提到的,你可以只使用c.moveToFirst()的返回值在有条件的:

 如果(c.moveToFirst()){
    串passwordAttachedToUsername = c.getString(1);
    如果(passwordAttachedToUsername.equals(密码)){
        认证= TRUE;
    }
}
 

For some reason when the username I input is not found, the application crashes. But when the username is found it seems to run perfect. I even do a check to see if the returned cursor == null. Heres the code

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

解决方案

Your Cursor object may not be null, but the size of its result set is 0. Instead of:

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

try:

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

Also, as @mu is too short mentioned, you could just use the return value of c.moveToFirst() in your conditional:

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

阅读全文

相关推荐

最新文章