Android中使用SimpleCursorAdapter报错

Android 做棵大树 6年前 (2018-05-25) 1862次浏览 0个评论

最近刚学了Android中的数据库存储 SQLite 数据库,在仿照着书上的例子写一个电话簿,然而在运行的过程中则是出现了以下的错误。

Android 中使用 SimpleCursorAdapter 报错

这是我的代码部分

try{
            Cursor cursor = db.rawQuery("select * from contact",null);
            inflateList(cursor);
        }catch (SQLiteException e){
            db.execSQL("create table contact(<span style="color: #800000;"><strong>id integer</strong></span> "+"primary key autoincrement,"
                    +"name varchar(50),"+"telephone varchar(50))");
            Cursor cursor = db.rawQuery("select * from contact",null);
            inflateList(cursor);
        }
——————————————————————————————————————
private void inflateList(Cursor cursor){
        //填充 simplecursorAdapter
       SimpleCursorAdapter sca = new SimpleCursorAdapter(MainActivity.this, R.layout.show,   cursor,
                new String[]{"name","telephone"},
                new int[]{R.id.my_name,R.id.my_telephone},CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        listView.setAdapter(sca);
    }

注意代码中的红色字块,原来我是想用 id 比较容易,然而缺少了一列 _id。

_id 是用来干什么的?

SimpleCursorAdapter 只识别 _id 作为主键

所以我们需要把上面查询的代码修改一下,添加一个 _id 的值


做棵大树 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明Android 中使用 SimpleCursorAdapter 报错
喜欢 (2)
[欢迎投币]
分享 (0)
关于作者:
一个整天无所事事的,有时候忽然热血的孩子
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址