Android 增加新值Adding newvalues

一旦记录已经存在,你就可以添加新的信息或修改已有信息。

比如,上例中的下一步就是添加联系人信息-如一个电话号码或一个即时通讯IM 或电子邮箱地址-到新的条目中。

在联系人数据库中增加一条记录的最佳途径是在该记录URI 后扩展表名,然后使用这个修正的URI 来添加新的数据值。

为此,每个联系人表暴露一个CONTENT_DIRECTORY 常量的表名。

下面的代码继续之前的例子,为上面刚刚创建的记录添加一个电话号码和电子邮件地址: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 = Uri.withAppendedPath(uri, People.Phones.CONTENT_DIRECTORY); values.clear(); values.put(People.Phones.TYPE, People.Phones.TYPE_MOBILE); values.put(People.Phones.NUMBER, "1233214567"); getContentResolver().insert(phoneUri, values); // Now add an email address in the same way. emailUri = Uri.withAppendedPath(uri, People.ContactMethods.CONTENT_DIRECTORY); values.clear(); // ContactMethods.KIND is used to distinguish different kinds of // contact methods, such as email, IM, etc. values.put(People.ContactMethods.KIND, Contacts.KIND_EMAIL); values.put(People.ContactMethods.DATA, "[email protected]"); values.put(People.ContactMethods.TYPE, People.ContactMethods.TYPE_HOME); getContentResolver().insert(emailUri, values); 你可以通过调用接收字节流的ContentValues.put()版本来把少量的二进制数据放到一张表格里去。

这对于像小图标或短小的音频片断这样的数据是可行的。

但是,如果你有大量二进制数据需要添加,比如一张相片或一首完整的歌曲,则需要把该数据的content: URI 放到表里然后以该文件的URI 调用ContentResolver.openOutputStream() 方法。

(这导致内容提供器把数据保存在一个文件里并且记录文件路径在这个记录的一个隐藏字段中。)

考虑到这一点,MediaStore 内容提供器,这个用来分发图像,音频和视频数据的主内容提供器,利用了一个特殊的约定:用来获取关于这个二进制数据的元信息的query()或managedQuery()方法使用的URI,同样可以被openInputStream()方法用来数据本身。

类似的,用来把元信息放进一个MediaStore记录里的insert()方法使用的URI,同样可以被openOutputStream()方法用来在那里存放二进制数据。

下面的代码片断说明了这个约定:import android.provider.MediaStore.Images.Media; import android.content.ContentValues; import java.io.OutputStream; // Save the name and description of an image in a ContentValues map. ContentValues values = new ContentValues(3); values.put(Media.DISPLAY_NAME, "road_trip_1"); values.put(Media.DESCRIPTION, "Day 1, trip to Los Angeles"); values.put(Media.MIME_TYPE, "image/jpeg"); // Add a new record without the bitmap, but with the values just set. // insert() returns the URI of the new record. Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values); // Now get a handle to the file for that record, and save the data into it. // Here, sourceBitmap is a Bitmap object representing the file to save to the database. try { OutputStream outStream = getContentResolver().openOutputStream(uri); sourceBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream); outStream.close(); } catch (Exception e) { Log.e(TAG, "exception while writing image", e); }