那些年Cursor上遇到的坑

    xiaoxiao2022-07-14  139

    Android Cursor 使用用法

    Android数据库查询的话我还是比较喜欢SQL的原生语句,感觉用上去比较舒服。既然说是坑,让我来上一个刚才踩的一个坑… String wxid = (String) XposedHelpers.getObjectField(item, "field_content"); cursor = db.rawQuery("select public_key from FriendTable where wxid =?;", new String[]{wxid}); if (cursor.getCount() == 1) { XposedBridge.log("解密秘钥获取成功"); key = cursor.getColumnName(0); } /** * private static String FRIEND_TABEL = "CREATE TABLE IF NOT EXISTS" + * " FriendTable(wxid TEXT,id INTEGER PRIMARY KEY" + * " , note TEXT, public_key TEXT, isEnc INTEGER, " + * "isDec INTEGER, BELONG INTEGER);";*/

    本意获取数据库的值$wxid的值(unique唯一的),但是上当了。假设我取出来3行数据 cursor是 zero-based 基于0开始编码。则三行行下标分别为(0,1,2) 但是由于cursor初始的行下标为(-1)直接开干会报错… 。所说还是需要将其移动到0位置开始

    cursor.moveToFirst() public abstract boolean moveToFirst () Move the cursor to the first row. This method will return false if the cursor is empty. 或者: cursor.moveToNext() public abstract boolean moveToNext () Move the cursor to the next row. This method will return false if the cursor is already past the last entry in the result set. 针对我的这个情况(返回行数要么为0要么为1 :判断是否返回并且取回返回的值—>如果有返回值) 直接上moveTonex()就Ok了 String wxid = (String) XposedHelpers.getObjectField(item, "field_content"); cursor = db.rawQuery("select public_key from FriendTable where wxid =?;", new String[]{wxid}); if (cursor.moveToNext()) { key = cursor.getColumnName(0); XposedBridge.log("解密秘钥获取成功"); } 就是这样哈哈 一般的返回有多行的处理模板 if (cursor.moveToFirst()) { do { /*********************** * dosomething * *********************/ } while (cursor.moveToNext()); }
    最新回复(0)