今天补充关于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有做特别的处理。
view plaincopy to clipboardprint?
1. private void insert() {
2. ContentValues cvalues = new ContentValues();
3. cvalues.put(PeopleColumns.NAME, "Liu,Xiaohua");
4. cvalues.put(PeopleColumns.TIMES_CONTACTED, 5);
5. Uri uri = getContentResolver().insert(People.CONTENT_URI, cvalues);
6. Log.i("lily","Insert succeed!");
7. Log.i("lily","uri = " + uri);
8. Uri phoneuri = Uri.withAppendedPath(uri, People.Phones.CONTENT_DIRECTORY);
9. Log.i("lily","phoneuri = " + phoneuri);
10. cvalues.clear();
11. cvalues.put(People.Phones.NUMBER, "110");
12. cvalues.put(People.Phones.TYPE, People.Phones.TYPE_MOBILE);
13. Uri resulturi = getContentResolver().insert(phoneuri, cvalues);
14. Log.i("lily","resulturi = "+resulturi);
15. }
Update:我将name=Liu,Xiaohua的数据的phone number进行了更新,这里查询时Liu,Xiaohua要加‘’单引号,不然会报错
view plaincopy to clipboardprint?
1. private void update() {
2. ContentResolver cr = getContentResolver();
3. String[] projection = {People._ID, People.PRIMARY_PHONE_ID};
4. Cursor cursor = cr.query(People.CONTENT_URI, projection, PeopleColumns.NAME + " = 'Liu,Xiaohua'", null, null);
5. if (cursor.moveToFirst()){
6. int id = cursor.getInt(cursor.getColumnIndex(People.PRIMARY_PHONE_ID));
7. ContentValues updateValues = new ContentValues();
8. updateValues.put(People.Phones.NUMBER, "114");
9. Uri updateUri = ContentUris.withAppendedId(Phones.CONTENT_URI, id);
10.
11. Log.i("lily","updateUri = "+updateUri);
12. cr.update(updateUri, updateValues, null, null);
13. }
14. else{
15. Log.i("lily","not found \"Liu,Xiaohua\"");
16. }
17. cursor.close();
18. }
delete:将我之前折腾的Liu,Xiaohua数据给删掉。每次操作的结果都可以去contact这个AP去看
view plaincopy to clipboardprint?
1. private void delete() {
2. int row = getContentResolver().delete(People.CONTENT_URI, People.NAME + " = 'Liu,Xiaohua'", null);
3. Log.i("lily","deleted " + row + " rows.");
4. }