学习ContentProvider---之二:Modify data:insert,update,delete

今天补充关于modify data的内容,Google的官方文档上是这样讲的:

 

修改数据库的几种可能:

·         Adding new records

·         Adding new values to existing records

·         Batch updating existing records(批量更新现有记录)

·         Deleting records

所有的修改操作都经由ContentResolver来进行,有些数据库对写操作比较严格,需要使用permission,例如我下面使用到的

凡是对contact进行写操作,那就必须加这个。

 

其实我总结起来就是insert和update就需要准备好ContentValues和ContentResolver,ContentValues把数据put好,然后开ContentResolver执行insert或update就好啦。批量更新我没看出有什么特别的,不确定文档的意思是说可以有方法去批量更新还是自己要查出来,然后一条条去更新。

 

 

文档上对openOutputStream和openInputStream废话了很久还写了一个小例子,这个我没有做实验,可能要等我的provider写出来再实验

 

以下是我写得insert, update,和delete三个动作:

Insert:这里面比较特别的是People.Phones.CONTENT_DIRECTORY的用法,具体怎么这样就能插入数据应该是因为provider中有针对这种格式的处理,因为我把这几个Uri打印出来看了,插入people表后,返回的uri是:content://contacts/people/7,而拼接后的Uri是:content://contacts/people/7/phones,但插入phones成功后返回的uri是:content://contacts/phones/5,所以这其中如何跳转的,我觉得provider有做特别的处理。

private void insert() { ContentValues cvalues = new ContentValues(); cvalues.put(PeopleColumns.NAME, "Liu,Xiaohua"); cvalues.put(PeopleColumns.TIMES_CONTACTED, 5); Uri uri = getContentResolver().insert(People.CONTENT_URI, cvalues); Log.i("lily","Insert succeed!"); Log.i("lily","uri = " + uri); Uri phoneuri = Uri.withAppendedPath(uri, People.Phones.CONTENT_DIRECTORY); Log.i("lily","phoneuri = " + phoneuri); cvalues.clear(); cvalues.put(People.Phones.NUMBER, "110"); cvalues.put(People.Phones.TYPE, People.Phones.TYPE_MOBILE); Uri resulturi = getContentResolver().insert(phoneuri, cvalues); Log.i("lily","resulturi = "+resulturi); } 

Update:我将name=Liu,Xiaohua的数据的phone number进行了更新,这里查询时Liu,Xiaohua要加‘’单引号,不然会报错

private void update() { ContentResolver cr = getContentResolver(); String[] projection = {People._ID, People.PRIMARY_PHONE_ID}; Cursor cursor = cr.query(People.CONTENT_URI, projection, PeopleColumns.NAME + " = 'Liu,Xiaohua'", null, null); if (cursor.moveToFirst()){ int id = cursor.getInt(cursor.getColumnIndex(People.PRIMARY_PHONE_ID)); ContentValues updateValues = new ContentValues(); updateValues.put(People.Phones.NUMBER, "114"); Uri updateUri = ContentUris.withAppendedId(Phones.CONTENT_URI, id); Log.i("lily","updateUri = "+updateUri); cr.update(updateUri, updateValues, null, null); } else{ Log.i("lily","not found /"Liu,Xiaohua/""); } cursor.close(); } 

delete:将我之前折腾的Liu,Xiaohua数据给删掉。每次操作的结果都可以去contact这个AP去看

private void delete() { int row = getContentResolver().delete(People.CONTENT_URI, People.NAME + " = 'Liu,Xiaohua'", null); Log.i("lily","deleted " + row + " rows."); } 

 

你可能感兴趣的:(android)