Java Code Examples for android.content.ContentValues#remove()

The following examples show how to use android.content.ContentValues#remove() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DBProxy.java    From android-orm with Apache License 2.0 6 votes vote down vote up
/**
 * 更具条件更新实体到数据库
 *
 * @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;
}
 
Example 2
Source File: QuantumFluxSyncHelper.java    From QuantumFlux with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 3
Source File: CategoryHandler.java    From opentasks with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 4
Source File: SubscriptionsDb.java    From SkyTube with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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);
			}
		}
	}
}
 
Example 5
Source File: CategoryHandler.java    From opentasks-provider with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 6
Source File: CPSyncHelper.java    From CPOrm with MIT License 6 votes vote down vote up
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);
}
 
Example 7
Source File: CustomContentProvider.java    From OpenCircle with GNU General Public License v3.0 5 votes vote down vote up
@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);
}
 
Example 8
Source File: PropertyHandler.java    From opentasks with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 9
Source File: ApkProvider.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
@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;
}
 
Example 10
Source File: RelationHandler.java    From opentasks with Apache License 2.0 5 votes vote down vote up
@Override
public ContentValues cloneForNewTask(long newTaskId, ContentValues values)
{
    ContentValues newValues = super.cloneForNewTask(newTaskId, values);
    newValues.remove(Relation.RELATED_CONTENT_URI);
    return newValues;
}
 
Example 11
Source File: DatabaseImport.java    From financisto with GNU General Public License v2.0 5 votes vote down vote up
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());
        }
    }
    */
}
 
Example 12
Source File: InsertQuery.java    From wellsql with MIT License 5 votes vote down vote up
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();
    }
}
 
Example 13
Source File: QuantumFluxSyncHelper.java    From QuantumFlux with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 14
Source File: MmsDatabase.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 15
Source File: TrackLayer.java    From android_maplib with GNU Lesser General Public License v3.0 5 votes vote down vote up
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;
    }
 
Example 16
Source File: CPSyncHelper.java    From CPOrm with MIT License 5 votes vote down vote up
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);
}
 
Example 17
Source File: QuantumFlux.java    From QuantumFlux with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 18
Source File: AccountDb.java    From google-authenticator-android with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
}
 
Example 19
Source File: HistoryDao.java    From hipda with GNU General Public License v2.0 4 votes vote down vote up
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();
    }
}
 
Example 20
Source File: AntiSnsDelete.java    From WechatEnhancement with GNU General Public License v3.0 4 votes vote down vote up
private void handleCommentDelete(ContentValues contentValues) {
    String label = "[已删除]";
    contentValues.remove("commentflag");
    contentValues.put("curActionBuf", notifyCommentDelete(label, contentValues.getAsByteArray("curActionBuf")));
}