Книга: Beginning Android

insert()

insert()

Your insert() method will receive a Uri representing the collection and a ContentValues structure with the initial data for the new instance. You are responsible for creating the new instance, filling in the supplied data, and returning a Uri to the new instance.

If this is a SQLite-backed content provider, once again, the implementation is mostly boilerplate: validate that all required values were supplied by the activity, merge your own notion of default values with the supplied data, and call insert() on the database to actually create the instance.

For example, here is insert() from Provider:

@Override
public Uri insert(Uri url, ContentValues initialValues) {
 long rowID;
 ContentValues values;
 if (initialValues!=null) {
  values = new ContentValues(initialValues);
 } else {
  values = new ContentValues();
 }
 if (!isCollectionUri(url)) {
  throw new IllegalArgumentException("Unknown URL " + url);
 }
 for (String colName : getRequiredColumns()) {
  if (values.containsKey(colName) == false) {
   throw new IllegalArgumentException("Missing column: " + colName);
  }
 }
 populateDefaultValues(values);
 rowID = db.insert(getTableName(), getNullColumnHack(), values);
 if (rowID > 0) {
  Uri uri = ContentUris.withAppendedId(getContentUri(), rowID);
  getContext().getContentResolver().notifyChange(uri, null);
  return uri;
 }
 throw new SQLException("Failed to insert row into " + url);
}

The pattern is the same as before: use the provider particulars plus the data to be inserted to actually do the insertion. Please note the following:

• You can insert only into a collection Uri, so we validate that by calling isCollectionUri().

• The provider knows what columns are required (getRequiredColumns()), so we iterate over those and confirm our supplied values cover the requirements.

• The provider is responsible for filling in any default values (populateDefaultValues()) for columns not supplied in the insert() call and not automatically handled by the SQLite table definition.

Оглавление книги

Оглавление статьи/книги

Генерация: 1.893. Запросов К БД/Cache: 2 / 0
поделиться
Вверх Вниз