那些年Cursor上遇到的坑

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值