[摘要]北大青鸟西安兆隆: Android某些 content providers写数据需要比读数据更严格的权限,如果没有写Content Provider的权限, ContentResolver的方法将失效。添加数据要想在Content Provider添加一条新纪录,首先要在ContentValues对象中创建一个键-值对的映射,在这个映射中,每个值对应c
某些content providers写数据需要比读数据更严格的权限,如果没有写Content Provider的权限, ContentResolver的方法将失效。添加数据要想在Content Provider添加一条新纪录,首先要在ContentValues对象中创建一个键-值对的映射,在这个映射中,每个值对应content provider中列的名字,相应的值就是新纪录在对应列中的值。然后,调用以Provider的URI和ContentValues映射作为参数 ***()函数。这个函数返回值是新记录的完整URI——即Provider的RUI加上新纪录的ID。可以通过这个URI查询和得到新纪录的Cursor,并且可以进一步修改这个新增加的记录。
复制到剪贴板 Java代码
-
import ***;
-
import ***tResolver;
-
import ***tValues;
-
-
ContentValues values = new ContentValues();
-
// Add Abraham Lincoln to contacts and make him a favorite. ***(***, "Abraham Lincoln");
-
// 1 = the new contact is added to favorites
-
// 0 = the new contact is not added to favorites ***(***D, 1);
-
-
Uri uri = getContentResolver().insert(***T_URI, values);
添加新值如果一条记录已经存在,我们可以为其增加新信息或者修改现有的信息。例如,上面例子的下一步是为这个新纪录增加联络信息——电话号、IM或电子邮件地址。为联系人数据库中增加一条新纪录最佳方法是把新数据所去的表明添加到该记录的URI后面,然后使用修正后的RUI来添加新数据值。每个联系人表都开放了一个名字作为CONTENT_DIRECTORY常量。 下面的代码接续前面的例子,为刚刚创建的记录增加电话号码和电邮地址。
复制到剪贴板 Java代码
-
Uri phoneUri = null;
-
Uri emailUri = null;
-
-
// Add a phone number for Abraham Lincoln. Begin with the URI for
-
// the new record just returned by insert();
-
-
it ends with the _ID
-
-
// of the new record, so we don't have to add the ID ourselves.
-
// Then append the designation for the phone table to this URI,
-
/* and use the resulting URI to insert the phone number. phoneUri = ***pendedPath(uri, ***T_DIRECTORY);*/
-
-
***();
-
***(***, ***_MOBILE);
-
***(***, "***");
-
getContentResolver().insert(phoneUri, values);
复制到剪贴板 Java代码
-
// Now add an email address in the same way. emailUri = ***pendedPath(uri,
-
-
***T_DIRECTORY); ***();
-
-
// *** is used to distinguish different kinds of
-
-
/*contact methods, such as email, IM, etc. ***(People.***, ***_EMAIL);*/
-
-
***(***, eoeandroid@eoemobile.com);
-
-
***(***, ***_HOME);
-
-
getContentResolver().insert(emailUri, values);
(责任编辑:北大青鸟西安兆隆)