android.content.ContentValues#remove ( )源码实例Demo

下面列出了android.content.ContentValues#remove ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: opentasks   文件: CategoryHandler.java
/**
 * Check if a category with matching {@link ContentValues} exists and returns the existing category or creates a new category in the database.
 *
 * @param db
 *         The {@link SQLiteDatabase}.
 * @param values
 *         The {@link ContentValues} of the category.
 *
 * @return The {@link ContentValues} of the existing or new category.
 */
private ContentValues getOrInsertCategory(SQLiteDatabase db, ContentValues values)
{
    if (values.getAsBoolean(IS_NEW_CATEGORY))
    {
        // insert new category in category table
        ContentValues newCategoryValues = new ContentValues(4);
        newCategoryValues.put(Categories.ACCOUNT_NAME, values.getAsString(Categories.ACCOUNT_NAME));
        newCategoryValues.put(Categories.ACCOUNT_TYPE, values.getAsString(Categories.ACCOUNT_TYPE));
        newCategoryValues.put(Categories.NAME, values.getAsString(Category.CATEGORY_NAME));
        newCategoryValues.put(Categories.COLOR, values.getAsInteger(Category.CATEGORY_COLOR));

        long categoryID = db.insert(Tables.CATEGORIES, "", newCategoryValues);
        values.put(Category.CATEGORY_ID, categoryID);
    }

    // remove redundant values
    values.remove(IS_NEW_CATEGORY);
    values.remove(Categories.ACCOUNT_NAME);
    values.remove(Categories.ACCOUNT_TYPE);

    return values;
}
 
源代码2 项目: opentasks-provider   文件: CategoryHandler.java
/**
 * Check if a category with matching {@link ContentValues} exists and returns the existing category or creates a new category in the database.
 * 
 * @param db
 *            The {@link SQLiteDatabase}.
 * @param values
 *            The {@link ContentValues} of the category.
 * @return The {@link ContentValues} of the existing or new category.
 */
private ContentValues getOrInsertCategory(SQLiteDatabase db, ContentValues values)
{
	if (values.getAsBoolean(IS_NEW_CATEGORY))
	{
		// insert new category in category table
		ContentValues newCategoryValues = new ContentValues(4);
		newCategoryValues.put(Categories.ACCOUNT_NAME, values.getAsString(Categories.ACCOUNT_NAME));
		newCategoryValues.put(Categories.ACCOUNT_TYPE, values.getAsString(Categories.ACCOUNT_TYPE));
		newCategoryValues.put(Categories.NAME, values.getAsString(Category.CATEGORY_NAME));
		newCategoryValues.put(Categories.COLOR, values.getAsInteger(Category.CATEGORY_COLOR));

		long categoryID = db.insert(Tables.CATEGORIES, "", newCategoryValues);
		values.put(Category.CATEGORY_ID, categoryID);
	}

	// remove redundant values
	values.remove(IS_NEW_CATEGORY);
	values.remove(Categories.ACCOUNT_NAME);
	values.remove(Categories.ACCOUNT_TYPE);

	return values;
}
 
源代码3 项目: SkyTube   文件: SubscriptionsDb.java
/**
 * Loop through each video saved in the passed {@link YouTubeChannel} and insert it into the database, or update it.
 * @param videos the list of videos
 * @param channelId the channel id
 */
public void saveVideos(List<YouTubeVideo> videos, String channelId) {
	SQLiteDatabase db = getWritableDatabase();
	for (YouTubeVideo video : videos) {
		if (video.getPublishDate() != null) {
			ContentValues values = createContentValues(video, channelId);
			if (hasVideo(video)) {
				values.remove(SubscriptionsVideosTable.COL_YOUTUBE_VIDEO_ID);
				db.update(SubscriptionsVideosTable.TABLE_NAME,
                           values,
                           SubscriptionsVideosTable.COL_YOUTUBE_VIDEO_ID_EQUALS_TO,
						new String[]{video.getId()});
			} else {
				db.insert(SubscriptionsVideosTable.TABLE_NAME, null, values);
			}
		}
	}
}
 
源代码4 项目: android-orm   文件: DBProxy.java
/**
 * 更具条件更新实体到数据库
 *
 * @param t
 * @param where
 * @param args
 * @param <T>
 * @return
 */
public final <T extends IDColumn> int update(T t, String where, String... args) {
    if (t == null) {
        throw new NullPointerException("更新对象为NULL!");
    }
    if (where == null || where.trim().length() < 1) {
        throw new NullPointerException("缺少WHERE条件语句!");
    }
    ClassInfo<T> classInfo = getClassInfo(t);
    String tableName = classInfo.getTableName();
    ContentValues values = classInfo.getContentValues(t);
    if (values.size() < 1) {
        return -1;
    }
    values.remove(IDColumn.PRIMARY_ID);
    SQLiteDatabase database = getDatabase();
    database.beginTransaction();
    int row = database.update(tableName, values, where, args);
    database.setTransactionSuccessful();
    database.endTransaction();
    close(database);
    return row;
}
 
源代码5 项目: QuantumFlux   文件: QuantumFluxSyncHelper.java
public static <T> void updateColumns(Context context, ContentProviderClient provider, T dataModelObject, String... columns) throws RemoteException {
    TableDetails tableDetails = QuantumFlux.findTableDetails(dataModelObject.getClass());
    ContentValues contentValues = ModelInflater.deflate(tableDetails, dataModelObject);
    Object columnValue = ModelInflater.deflateColumn(tableDetails, tableDetails.findPrimaryKeyColumn(), dataModelObject);
    Uri itemUri = UriMatcherHelper.generateItemUriBuilder(tableDetails, String.valueOf(columnValue))
            .appendQueryParameter(QuantumFluxContentProvider.PARAMETER_SYNC, "false").build();

    for (String contentColumn : tableDetails.getColumnNames()) {
        boolean includeColumn = false;
        for (String column : columns) {
            if (contentColumn.equals(column)) {
                includeColumn = true;
                break;
            }
        }

        if (!includeColumn) contentValues.remove(contentColumn);
    }

    provider.update(itemUri, contentValues, null, null);
}
 
源代码6 项目: CPOrm   文件: CPSyncHelper.java
public static <T> void updateColumns(Context context, boolean notifyChanges, ContentProviderClient provider, T dataModelObject, String... columns) throws RemoteException {
    TableDetails tableDetails = CPOrm.findTableDetails(context, dataModelObject.getClass());
    ContentValues contentValues = ModelInflater.deflate(tableDetails, dataModelObject);
    Object columnValue = ModelInflater.deflateColumn(tableDetails, tableDetails.findPrimaryKeyColumn(), dataModelObject);
    Uri itemUri = UriMatcherHelper.generateItemUri(context, tableDetails, String.valueOf(columnValue))
            .appendQueryParameter(CPOrmContentProvider.PARAMETER_SYNC, "false")
            .appendQueryParameter(CPOrmContentProvider.PARAMETER_NOTIFY_CHANGES, Boolean.toString(notifyChanges)).build();

    for (String contentColumn : tableDetails.getColumnNames()) {

        boolean includeColumn = false;
        for (String column : columns) {
            if (contentColumn.equals(column)) {
                includeColumn = true;
                break;
            }
        }

        if (!includeColumn)
            contentValues.remove(contentColumn);
    }

    provider.update(itemUri, contentValues, null, null);
}
 
源代码7 项目: financisto   文件: DatabaseImport.java
private void cleanupValues(String tableName, ContentValues values) {
    // remove system entities
    Integer id = values.getAsInteger("_id");
    if (id != null && id <= 0) {
        Log.w("Financisto", "Removing system entity: " + values);
        values.clear();
        return;
    }
    // fix columns
    values.remove("updated_on");
    values.remove("remote_key");
    if (LOCATIONS_TABLE.equals(tableName)) {
        if (values.containsKey("name")) {
            values.put("title", values.getAsString("name"));
        }
    } else if (ATTRIBUTES_TABLE.equals(tableName)) {
        if (values.containsKey("name")) {
            values.put("title", values.getAsString("name"));
            values.remove("name");
        }
    }
    // remove unknown columns
    String sql = "select * from " + tableName + " WHERE 1=0";
    try (Cursor c = db.rawQuery(sql, null)) {
        final String[] columnNames = c.getColumnNames();
        removeUnknownColumns(values, columnNames, tableName);
    }

    /*
    if ("account".equals(tableName)) {
        values.remove("sort_order");
        String type = values.getAsString("type");
        if ("PAYPAL".equals(type)) {
            values.put("type", AccountType.ELECTRONIC.name());
            values.put("card_issuer", ElectronicPaymentType.PAYPAL.name());
        }
    }
    */
}
 
源代码8 项目: opentasks   文件: RelationHandler.java
@Override
public ContentValues cloneForNewTask(long newTaskId, ContentValues values)
{
    ContentValues newValues = super.cloneForNewTask(newTaskId, values);
    newValues.remove(Relation.RELATED_CONTENT_URI);
    return newValues;
}
 
源代码9 项目: opentasks   文件: PropertyHandler.java
public ContentValues cloneForNewTask(long newTaskId, ContentValues values)
{
    ContentValues newValues = new ContentValues(values);
    newValues.remove(Properties.PROPERTY_ID);
    newValues.put(Properties.TASK_ID, newTaskId);
    return newValues;
}
 
源代码10 项目: OpenCircle   文件: CustomContentProvider.java
@Override
public Uri insert(Uri uri, ContentValues values) {
    TABLE_NAME = values.getAsString("table_name");
    values.remove("table_name");

    long rowID = db.insert(TABLE_NAME, "", values);
    if (rowID > 0) {
        Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
        getContext().getContentResolver().notifyChange(_uri, null);
        return _uri;
    }
    throw new SQLException("Failed to add a record into " + uri);
}
 
源代码11 项目: fdroidclient   文件: ApkProvider.java
@Override
public int update(@NonNull Uri uri, ContentValues values, String where, String[] whereArgs) {
    if (MATCHER.match(uri) != CODE_APK_FROM_REPO) {
        throw new UnsupportedOperationException("Cannot update anything other than a single apk.");
    }

    boolean saveAntiFeatures = false;
    String[] antiFeatures = null;
    if (values.containsKey(Cols.AntiFeatures.ANTI_FEATURES)) {
        saveAntiFeatures = true;
        String antiFeaturesString = values.getAsString(Cols.AntiFeatures.ANTI_FEATURES);
        antiFeatures = Utils.parseCommaSeparatedString(antiFeaturesString);
        values.remove(Cols.AntiFeatures.ANTI_FEATURES);
    }

    validateFields(Cols.ALL, values);
    removeFieldsFromOtherTables(values);

    QuerySelection query = new QuerySelection(where, whereArgs);
    query = query.add(querySingleWithAppId(uri));

    int numRows = db().update(getTableName(), values, query.getSelection(), query.getArgs());

    if (saveAntiFeatures) {
        // Get the database ID of the row we just updated, so that we can join relevant anti features to it.
        Cursor result = db().query(getTableName(), new String[]{Cols.ROW_ID},
                query.getSelection(), query.getArgs(), null, null, null);
        if (result != null) {
            result.moveToFirst();
            long apkId = result.getLong(0);
            ensureAntiFeatures(antiFeatures, apkId);
            result.close();
        }
    }

    if (!isApplyingBatch()) {
        getContext().getContentResolver().notifyChange(uri, null);
    }
    return numRows;
}
 
源代码12 项目: wellsql   文件: InsertQuery.java
public void execute() {
    try {
        if (mToInsert.isEmpty()) {
            mAsTransaction = false;
            return;
        }
        if (mAsTransaction) {
            mDb.beginTransaction();
        }
        for (T item : mToInsert) {
            ContentValues cv = mMapper.toCv(item);
            //We do this not to violate UNIQUE constraint of @PrimaryKey, when using generated mapper
            if (mTable.shouldAutoincrementId()) {
                cv.remove("_id");
            }
            int index = (int) mDb.insert(mTable.getTableName(), null, cv);
            item.setId(index);
        }
        if (mAsTransaction) {
            mDb.setTransactionSuccessful();
        }
    } finally {
        if (mAsTransaction) {
            mDb.endTransaction();
        }
        mDb.close();
    }
}
 
源代码13 项目: Silence   文件: MmsDatabase.java
public long insertMessageOutbox(MasterSecret masterSecret, OutgoingMediaMessage message,
                                long threadId, boolean forceSms)
    throws MmsException
{
  long type = Types.BASE_SENDING_TYPE | Types.ENCRYPTION_SYMMETRIC_BIT;

  if (message.isSecure()) type |= Types.SECURE_MESSAGE_BIT;
  if (forceSms)           type |= Types.MESSAGE_FORCE_SMS_BIT;

  List<String> recipientNumbers = message.getRecipients().toNumberStringList(true);

  MmsAddresses addresses;

  if (!message.getRecipients().isSingleRecipient() &&
       message.getDistributionType() == ThreadDatabase.DistributionTypes.BROADCAST)
  {
    addresses = MmsAddresses.forBcc(recipientNumbers);
  } else {
    addresses = MmsAddresses.forTo(recipientNumbers);
  }

  ContentValues contentValues = new ContentValues();
  contentValues.put(DATE_SENT, message.getSentTimeMillis());
  contentValues.put(MESSAGE_TYPE, PduHeaders.MESSAGE_TYPE_SEND_REQ);

  contentValues.put(MESSAGE_BOX, type);
  contentValues.put(THREAD_ID, threadId);
  contentValues.put(READ, 1);
  contentValues.put(DATE_RECEIVED, contentValues.getAsLong(DATE_SENT));
  contentValues.put(SUBSCRIPTION_ID, message.getSubscriptionId());
  contentValues.remove(ADDRESS);

  long messageId = insertMediaMessage(masterSecret, addresses, message.getBody(),
                                      message.getAttachments(), contentValues);

  DatabaseFactory.getThreadDatabase(context).setLastSeen(threadId);
  jobManager.add(new TrimThreadJob(context, threadId));

  return messageId;
}
 
源代码14 项目: android_maplib   文件: TrackLayer.java
public Uri insert(
            Uri uri,
            ContentValues values)
    {
        mSQLiteDatabase = mMap.getDatabase(false);
        long id;
        Uri inserted;

        switch (mUriMatcher.match(uri)) {
            case TYPE_SINGLE_TRACK:
                values.remove(FIELD_ID);
            case TYPE_TRACKS:
                id = mSQLiteDatabase.insert(TABLE_TRACKS, null, values);
                inserted = ContentUris.withAppendedId(mContentUriTracks, id);
                break;
            case TYPE_TRACKPOINTS:
                id = mSQLiteDatabase.insert(TABLE_TRACKPOINTS, null, values);
                inserted = ContentUris.withAppendedId(mContentUriTrackpoints, id);
                break;
            default:
                throw new IllegalArgumentException("Wrong tracks URI: " + uri);
        }

        if (id != NOT_FOUND) {
//            notifyLayerChanged();
            reloadTracks(INSERT);
            getContext().getContentResolver().notifyChange(inserted, null);
        }

        return inserted;
    }
 
源代码15 项目: CPOrm   文件: CPSyncHelper.java
public static <T> void updateColumnsExcluding(Context context, boolean notifyChanges, ContentProviderClient provider, T dataModelObject, String... columnsToExclude) throws RemoteException {
    TableDetails tableDetails = CPOrm.findTableDetails(context, dataModelObject.getClass());
    ContentValues contentValues = ModelInflater.deflate(tableDetails, dataModelObject);
    Object columnValue = ModelInflater.deflateColumn(tableDetails, tableDetails.findPrimaryKeyColumn(), dataModelObject);
    Uri itemUri = UriMatcherHelper.generateItemUri(context, tableDetails, String.valueOf(columnValue))
            .appendQueryParameter(CPOrmContentProvider.PARAMETER_SYNC, "false")
            .appendQueryParameter(CPOrmContentProvider.PARAMETER_NOTIFY_CHANGES, Boolean.toString(notifyChanges)).build();

    for (String columnToExclude : columnsToExclude) {

        contentValues.remove(columnToExclude);
    }

    provider.update(itemUri, contentValues, null, null);
}
 
源代码16 项目: QuantumFlux   文件: QuantumFlux.java
public static <T> void updateColumnsExcluding(T dataModelObject, String... columnsToExclude) {
    TableDetails tableDetails = findTableDetails(dataModelObject.getClass());
    ContentValues contentValues = ModelInflater.deflate(tableDetails, dataModelObject);
    Object columnValue = ModelInflater.deflateColumn(tableDetails, tableDetails.findPrimaryKeyColumn(), dataModelObject);
    Uri itemUri = UriMatcherHelper.generateItemUriBuilder(tableDetails, String.valueOf(columnValue)).build();

    for (String columnToExclude : columnsToExclude) {
        contentValues.remove(columnToExclude);
    }

    ContentResolver contentResolver = mApplicationContext.getContentResolver();
    contentResolver.update(itemUri, contentValues, null, null);
}
 
源代码17 项目: QuantumFlux   文件: QuantumFluxSyncHelper.java
public static <T> void updateColumnsExcluding(Context context, ContentProviderClient provider, T dataModelObject, String... columnsToExclude) throws RemoteException {
    TableDetails tableDetails = QuantumFlux.findTableDetails(dataModelObject.getClass());
    ContentValues contentValues = ModelInflater.deflate(tableDetails, dataModelObject);
    Object columnValue = ModelInflater.deflateColumn(tableDetails, tableDetails.findPrimaryKeyColumn(), dataModelObject);
    Uri itemUri = UriMatcherHelper.generateItemUriBuilder(tableDetails, String.valueOf(columnValue))
            .appendQueryParameter(QuantumFluxContentProvider.PARAMETER_SYNC, "false").build();

    for (String columnToExclude : columnsToExclude) {
        contentValues.remove(columnToExclude);
    }

    provider.update(itemUri, contentValues, null, null);
}
 
源代码18 项目: WechatEnhancement   文件: AntiSnsDelete.java
private void handleCommentDelete(ContentValues contentValues) {
    String label = "[已删除]";
    contentValues.remove("commentflag");
    contentValues.put("curActionBuf", notifyCommentDelete(label, contentValues.getAsByteArray("curActionBuf")));
}
 
源代码19 项目: google-authenticator-android   文件: AccountDb.java
/**
 * Adds the specified account into this database. An existing account with the same name and
 * issuer is overwritten by this operation, unless {@code issuer} is {@code null}. If the issuer
 * is {@code null}, then a new account will always be created by appending an incrementing
 * counter to {@code name} until it is unique amongst all account names with {@code null} issuer.
 *
 * @param name the desired account name (e.g., user's email address)
 * @param secret the secret key.
 * @param type hotp vs totp
 * @param counter only important for the hotp type
 * @param googleAccount whether the key is for a Google Account or {@code null} if this
 *        information is not available. In case this operation overwrites an existing account
 *        the value of the flag is not overwritten.
 * @param issuer the {@code issuer} parameter of the QR code if applicable, {@code null} otherwise
 * @return the actual {@link AccountIndex} of the record that was added
 * @throws AccountDbDuplicateLimitException if there are too many accounts with this name already
 */
public AccountIndex add(String name, String secret, OtpType type, Integer counter,
    Boolean googleAccount, String issuer) {
  Preconditions.checkNotNull(name);
  Preconditions.checkNotNull(secret);
  Preconditions.checkNotNull(type);
  if ((issuer != null) && (issuer.length() == 0)) {
    issuer = null; // Treat an empty issuer as null
  }

  ContentValues values = newContentValuesWith(secret, type, counter, googleAccount);
  AccountIndex indexToAdd = new AccountIndex(name, issuer);
  Log.i(LOCAL_TAG, "Adding account: " + indexToAdd);

  if ((issuer != null) || name.equals(GOOGLE_CORP_ACCOUNT_NAME)) {
    // When an issuer is set, we will overwrite the matching account if it already exists
    // (ditto for "Google Internal 2Factor" accounts, even though they have a null issuer).
    if (issuer != null) {
      values.put(ISSUER_COLUMN, issuer);
      AccountIndex similarIndex = findSimilarExistingIndex(indexToAdd);
      if (similarIndex != null) {
        Log.i(LOCAL_TAG, "Will overwrite similar account: " + similarIndex);
        indexToAdd = similarIndex;
      }
    }
    int updated = mDatabase.update(TABLE_NAME, values, whereClause(indexToAdd), null);
    if (updated == 0) {
      // No matching pre-existing account to update, so insert the new one
      values.put(NAME_COLUMN, name);
      // TODO: Add a test for the ORIGINAL_NAME_COLUMN behavior
      values.put(ORIGINAL_NAME_COLUMN, name);
      mDatabase.insert(TABLE_NAME, null, values);
    } else {
      Log.i(LOCAL_TAG, "Overwrote existing OTP seed for: " + indexToAdd);
    }
    if (!indexToAdd.getName().equals(name)) {
      // We overwrote a similar index with a different name, so now we try to rename it to match
      // the name requested by the add operation (if it is safe to do so)
      rename(indexToAdd, name);
    }
  } else {
    // No issuer is set, so we do not overwrite any existing account
    values.put(NAME_COLUMN, indexToAdd.getName());
    values.put(ORIGINAL_NAME_COLUMN, indexToAdd.getName());
    int tries = 0;
    while (!insertNewAccount(values)) {
      // There was already an account with this name
      tries++;
      if (tries >= MAX_DUPLICATE_NAMES) {
        // TODO: Make this a checked exception, and have the caller show an Alert for it
        throw new AccountDbDuplicateLimitException("Too many accounts with same name: " + name);
      }
      // Rename the account and try again
      indexToAdd = new AccountIndex(name + "(" + tries + ")", issuer);
      values.remove(NAME_COLUMN);
      values.put(NAME_COLUMN, indexToAdd.getName());
    }
  }
  return indexToAdd;
}
 
源代码20 项目: hipda   文件: HistoryDao.java
private synchronized static void saveHistory(
        String tid, String fid, String title,
        String uid, String username, String postTime) {

    if (!HiUtils.isValidId(tid))
        return;

    SQLiteDatabase db = null;
    Cursor cursor = null;
    try {
        db = HistoryDBHelper.getHelper().getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("tid", tid);

        if (!TextUtils.isEmpty(title))
            contentValues.put("title", title);
        if (!TextUtils.isEmpty(fid))
            contentValues.put("fid", fid);
        if (!TextUtils.isEmpty(uid))
            contentValues.put("uid", uid);
        if (!TextUtils.isEmpty(username))
            contentValues.put("username", username);
        if (!TextUtils.isEmpty(postTime))
            contentValues.put("post_time", postTime);

        contentValues.put("visit_time", System.currentTimeMillis());

        cursor = db.rawQuery(
                "select tid from " + HistoryDBHelper.TABLE_NAME +
                        " where tid=?", new String[]{tid});

        if (cursor.getCount() == 0) {
            db.insert(HistoryDBHelper.TABLE_NAME, null, contentValues);
        } else {
            contentValues.remove("tid");
            db.update(HistoryDBHelper.TABLE_NAME, contentValues, "tid=?", new String[]{tid});
        }
    } catch (Exception e) {
        Logger.e(e);
    } finally {
        if (cursor != null)
            cursor.close();
        if (db != null)
            db.close();
    }
}