Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在android中使用游标从数据库检索记录_Android_Database_Sqlite_Cursor - Fatal编程技术网

在android中使用游标从数据库检索记录

在android中使用游标从数据库检索记录,android,database,sqlite,cursor,Android,Database,Sqlite,Cursor,我使用以下代码检索记录: String getCredentialsFromAdmint(String name ,String pwd) { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(TABLE_ADMIN, new String[] { KEY_ID, KEY_A_USER_NAME, KEY_A_PWD }, KEY_A_

我使用以下代码检索记录:

String getCredentialsFromAdmint(String name ,String pwd) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_ADMIN, new String[] { KEY_ID,
                KEY_A_USER_NAME, KEY_A_PWD }, KEY_A_USER_NAME + "=?" + " AND " + KEY_A_PWD + "=?",
                new String[] { name , pwd }, null, null, null, null);

        if (cursor != null){
            cursor.moveToFirst();
        return cursor.getString(1);
        }
        else{
            return "norecord";
        }

如果存在记录,则此代码有效,但如果未找到任何记录,则应用程序将收到错误。
是否有其他方法从数据库检索数据?

您不检查cursor.moveToFirst()是否返回true

应该是这样的:

if (cursor != null) {
   if(cursor.moveToFirst()){
       return cursor.getString(cursor.getColumnIndexOrThrow(KEY_A_USER_NAME));
   } else{
     //no record
   }
} else {
   //invalid uri
}

请尝试使用以下代码

if (cursor != null){
    cursor.moveToFirst();
    if(cursor.isAfterLast() == false) {
    return cursor.getString(1);
    }
    else
    {
    return "norecord";
    }
}
else{
    return "norecord";
}

将代码更改为以下内容

 if ( cursor.moveToFirst()){
      return cursor.getString(1);
    } else{
        return "norecord";
    }