下面列出了android.content.ContentValues#size ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Update album in the database with the given ContentValues.
*/
private int updateAlbum(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
// If there are no values to update, then don't try to update the database
if (values.size() == 0) {
return 0;
}
// Sanity check values
if (!sanityCheckAlbum(values)) {
throw new IllegalArgumentException("Sanity check failed: corrupted content values");
}
// Get writable database
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// Update the table
int rowsUpdated = db.update(AnchorContract.AlbumEntry.TABLE_NAME, values, selection, selectionArgs);
// If 1 or more rows were updated, then notify all listeners that the data at the
// given URI has changed
if (rowsUpdated != 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return rowsUpdated;
}
private String concatenateInsert(Uri uri, ContentValues cv) {
StringBuilder sb = new StringBuilder();
sb.append(" insert into ");
sb.append("[" + uri.toString() + "]");
sb.append(" ( ");
String[] keysArray = new String[cv.size()];
keysArray = this.getContentValuesKeySet(cv).toArray(keysArray);
sb.append(concatenateStringArray(keysArray, ","));
sb.append(" ) ");
sb.append(" values (");
for (int i = 0; i < keysArray.length; i++) {
if (i == keysArray.length - 1)
sb.append(" " + cv.get(keysArray[i]));
else
sb.append(" " + cv.get(keysArray[i]) + ",");
}
sb.append(" )");
return sb.toString();
}
/**
* Update a ExternalAttribute record with specific parameters.
*
* @param attributeID
* is the id of the record to be updated.
* @param attributeName
* is the attribute name, or null if not updating it.
* @param appID
* is the application id, or null if not updating it.
* @param dataTypeID
* is the dataType id, or null if not updating it.
* @return true if success, or false otherwise.
* @throws IllegalArgumentException
* if attributeID is null
*/
public boolean update(Long attributeID, String attributeName, Long appID, Long dataTypeID) {
if (attributeID == null) {
throw new IllegalArgumentException("primary key null.");
}
ContentValues args = new ContentValues();
if (attributeName != null) {
args.put(KEY_EXTERNALATTRIBUTENAME, attributeName);
}
if (appID != null) {
args.put(KEY_APPID, appID);
}
if (dataTypeID != null) {
args.put(KEY_DATATYPEID, dataTypeID);
}
if (args.size() > 0) {
// Set whereArg to null here
return database.update(DATABASE_TABLE, args, KEY_EXTERNALATTRIBUTEID + "=" + attributeID,
null) > 0;
}
return false;
}
private String concatenateInsert(Uri uri, ContentValues cv) {
StringBuilder sb = new StringBuilder();
sb.append(" insert into ");
sb.append("[" + uri.toString() + "]");
sb.append(" ( ");
String[] keysArray = new String[cv.size()];
keysArray = this.getContentValuesKeySet(cv).toArray(keysArray);
sb.append(concatenateStringArray(keysArray, ","));
sb.append(" ) ");
sb.append(" values (");
for (int i = 0; i < keysArray.length; i++) {
if (i == keysArray.length - 1)
sb.append(" " + cv.get(keysArray[i]));
else
sb.append(" " + cv.get(keysArray[i]) + ",");
}
sb.append(" )");
return sb.toString();
}
@Override
public void save(T entity) throws DBException {
ContentValues values;
try {
openDB(true);
values = Utils.putValue(fields, entity);
if (values == null || values.size() <= 0) {
throw new DBException(ErrMsg.ERR_SAVE_PARAM);
}
long flag = db.insert(mTableName, null, values);
if (flag < 1) {
throw new DBException(ErrMsg.ERR_SAVE_PARAM);
}
} catch (Exception e) {
throw new DBException(ErrMsg.ERR_SAVE_PARAM, e);
} finally {
closeDB();
}
}
public void updateWallpaper(Wallpaper wallpaper) {
if (!openDatabase()) {
LogUtil.e("Database error: updateWallpaper() failed to open database");
return;
}
if (wallpaper == null) return;
ContentValues values = new ContentValues();
if (wallpaper.getSize() > 0) {
values.put(KEY_SIZE, wallpaper.getSize());
}
if (wallpaper.getMimeType() != null) {
values.put(KEY_MIME_TYPE, wallpaper.getMimeType());
}
if (wallpaper.getDimensions() != null) {
values.put(KEY_WIDTH, wallpaper.getDimensions().getWidth());
values.put(KEY_HEIGHT, wallpaper.getDimensions().getHeight());
}
if (wallpaper.getColor() != 0) {
values.put(KEY_COLOR, wallpaper.getColor());
}
if (values.size() > 0) {
mDatabase.get().mSQLiteDatabase.update(TABLE_WALLPAPERS,
values, KEY_URL + " = ?", new String[]{wallpaper.getURL()});
}
}
/**
* Update a RuleFilter record with specific parameters.
*
* @param ruleFilterID
* is id or the record.
* @param ruleID
* is the id of rule the filter belongs to, or null if not updating it.
* @param eventAttributeID
* is id of the event attribute, or null if not updating it.
* @param externalAttributeID
* is id of the external attribute, or null if not updating it.
* @param dataFilterID
* is id of the data filter, or null if not updating it.
* @param parentRuleFilterID
* is id of its parent ruleFiler, or null if not updating it.
* @param ruleFilterData
* is the data associated with this ruleFilter, or null if not updating it.
* @return true if success, or false otherwise.
* @throws IllegalArgumentException
* if ruleFilterID is null
*/
public boolean update(Long ruleFilterID, Long ruleID, Long eventAttributeID,
Long externalAttributeID, Long dataFilterID, Long parentRuleFilterID, String ruleFilterData) {
if (ruleFilterID == null) {
throw new IllegalArgumentException("primary key null.");
}
ContentValues args = new ContentValues();
if (ruleID != null) {
args.put(KEY_RULEID, ruleID);
}
if (eventAttributeID != null) {
args.put(KEY_EVENTATTRIBUTEID, eventAttributeID);
}
if (externalAttributeID != null) {
args.put(KEY_EXTERNALATTRIBUTEID, externalAttributeID);
}
if (dataFilterID != null) {
args.put(KEY_DATAFILTERID, dataFilterID);
}
if (parentRuleFilterID != null) {
args.put(KEY_PARENTRULEFILTERID, parentRuleFilterID);
}
if (ruleFilterData != null) {
args.put(KEY_RULEFILTERDATA, ruleFilterData);
}
if (args.size() > 0) {
// Set whereArg to null here
return database.update(DATABASE_TABLE, args, KEY_RULEFILTERID + "=" + ruleFilterID, null) > 0;
}
return false;
}
/**
* Returns true if the values is null or 0-length.
*
* @param values the values to be examined
* @return true if values is null or zero length
*/
public static boolean isEmpty(ContentValues values) {
if (values == null || values.size() == 0) {
return true;
} else {
return false;
}
}
/**
* Update a RegisteredApp record with specific parameters.
*
* @param appID
* is the id of the record to be updated.
* @param appName
* is the application name or null if not updating it.
* @param pkgName
* is the package name or null if not updating it.
* @param enabled
* is whether the application is activated or null if not updating it.
* @param loginEabled
* is whether the application needs username and password information.
* @param username
* is the username for the application.
* @param password
* is the password the application.
* @return true if success, or false otherwise.
* @throws IllegalArgumentException
* if appID is null
*/
public boolean update(Long appID, String appName, String pkgName, Boolean enabled,
Boolean loginEnabled, String username, String password) {
if (appID == null) {
throw new IllegalArgumentException("primary key null.");
}
ContentValues args = new ContentValues();
if (appName != null) {
args.put(KEY_APPNAME, appName);
}
if (pkgName != null) {
args.put(KEY_PKGNAME, pkgName);
}
if (enabled != null) {
args.put(KEY_ENABLED, enabled);
}
if (loginEnabled != null) {
args.put(KEY_LOGIN, loginEnabled);
}
if (username != null) {
args.put(KEY_USERNAME, username);
}
if (password != null) {
args.put(KEY_PASSWORD, password);
}
if (args.size() > 0) {
// Set whereArg to null here
return database.update(DATABASE_TABLE, args, KEY_APPID + "=" + appID, null) > 0;
}
return false;
}
@NonNull
public Insert<TModel> columnValues(@NonNull ContentValues contentValues) {
java.util.Set<Map.Entry<String, Object>> entries = contentValues.valueSet();
int count = 0;
String[] columns = new String[contentValues.size()];
Object[] values = new Object[contentValues.size()];
for (Map.Entry<String, Object> entry : entries) {
String key = entry.getKey();
columns[count] = key;
values[count] = contentValues.get(key);
count++;
}
return columns(columns).values(values);
}
/**
* 插入数据
*
* @param tableName
* @param values
* @return
*/
public final long insert(String tableName, ContentValues values) {
SQLiteDatabase database = getDatabase();
long id = -1;
database.beginTransaction();
if (values.size() > 0) {
id = database.insert(tableName, null, values);
}
database.setTransactionSuccessful();
database.endTransaction();
close(database);
return id;
}
/**
* Update user record
*
* @return true if the record was updated, false otherwise
*/
public static boolean update(SQLiteDatabase db, long userId, Date updated, Object pub) {
// Convert topic description to a map of values
ContentValues values = new ContentValues();
if (updated != null) {
values.put(COLUMN_NAME_UPDATED, updated.getTime());
}
if (pub != null) {
values.put(COLUMN_NAME_PUBLIC, BaseDb.serialize(pub));
}
return values.size() <= 0 || db.update(TABLE_NAME, values, _ID + "=" + userId, null) > 0;
}
/**
* General method for inserting a row into the database.
*
* @param table the table to insert the row into
* @param nullColumnHack optional; may be <code>null</code>.
* SQL doesn't allow inserting a completely empty row without
* naming at least one column name. If your provided <code>initialValues</code> is
* empty, no column names are known and an empty row can't be inserted.
* If not set to null, the <code>nullColumnHack</code> parameter
* provides the name of nullable column name to explicitly insert a NULL into
* in the case where your <code>initialValues</code> is empty.
* @param initialValues this map contains the initial column values for the
* row. The keys should be the column names and the values the
* column values
* @param conflictAlgorithm for insert conflict resolver
* @return the row ID of the newly inserted row OR <code>-1</code> if either the
* input parameter <code>conflictAlgorithm</code> = {@link #CONFLICT_IGNORE}
* or an error occurred.
*/
public long insertWithOnConflict(String table, String nullColumnHack,
ContentValues initialValues, int conflictAlgorithm) {
acquireReference();
try {
StringBuilder sql = new StringBuilder();
sql.append("INSERT");
sql.append(CONFLICT_VALUES[conflictAlgorithm]);
sql.append(" INTO ");
sql.append(table);
sql.append('(');
Object[] bindArgs = null;
int size = (initialValues != null && !initialValues.isEmpty())
? initialValues.size() : 0;
if (size > 0) {
bindArgs = new Object[size];
int i = 0;
for (String colName : initialValues.keySet()) {
sql.append((i > 0) ? "," : "");
sql.append(colName);
bindArgs[i++] = initialValues.get(colName);
}
sql.append(')');
sql.append(" VALUES (");
for (i = 0; i < size; i++) {
sql.append((i > 0) ? ",?" : "?");
}
} else {
sql.append(nullColumnHack + ") VALUES (NULL");
}
sql.append(')');
SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
try {
return statement.executeInsert();
} finally {
statement.close();
}
} finally {
releaseReference();
}
}
public static void updateFullNames(String tableName, boolean useFullName, SQLiteDatabase db) {
long t = System.currentTimeMillis();
String nameColumn;
if (tableName.equals(T_LOG_TRANSACTIONS)) {
nameColumn = useFullName ? getFullNameColumn(tableName) : C_LOG_TRANSACTIONS_COMMENT;
} else {
nameColumn = useFullName ? getFullNameColumn(tableName) : "Name";
}
String fields[];
if (useFullName) {
fields = new String[]{C_ID, nameColumn, C_SEARCH_STRING, C_FULL_NAME};
} else {
fields = new String[]{C_ID, nameColumn, C_SEARCH_STRING};
}
Cursor cursor = db.query(tableName, fields, "Deleted = 0", null, null, null, null);
ContentValues cv = new ContentValues();
String translit;
int i = 0;
try {
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
cv.clear();
if (useFullName) {
cv.put(C_FULL_NAME, cursor.getString(1));
}
translit = Translit.toTranslit(cursor.getString(1).toLowerCase());
if (!cursor.getString(2).equals(translit)) {
cv.put(C_SEARCH_STRING, translit);
}
if (cv.size() != 0) {
db.update(tableName, cv, "_id = " + cursor.getString(0), null);
}
cursor.moveToNext();
i++;
// Log.d(TAG, cursor.getString(0));
}
}
} finally {
cursor.close();
}
// t = System.currentTimeMillis() - t;
// Log.d(TAG, "Update full names in " + tableName + " - " + String.valueOf(t) + "ms");
}
public void insertContact(VCard vcard) throws RemoteException, OperationApplicationException {
// TODO handle Raw properties - Raw properties include various extension which start with "X-" like X-ASSISTANT, X-AIM, X-SPOUSE
List<NonEmptyContentValues> contentValues = new ArrayList<NonEmptyContentValues>();
convertName(contentValues, vcard);
convertNickname(contentValues, vcard);
convertPhones(contentValues, vcard);
convertEmails(contentValues, vcard);
convertAddresses(contentValues, vcard);
convertIms(contentValues, vcard);
// handle Android Custom fields..This is only valid for Android generated Vcards. As the Android would
// generate NickName, ContactEvents other than Birthday and RelationShip with this "X-ANDROID-CUSTOM" name
convertCustomFields(contentValues, vcard);
// handle Iphone kinda of group properties. which are grouped together.
convertGroupedProperties(contentValues, vcard);
convertBirthdays(contentValues, vcard);
convertWebsites(contentValues, vcard);
convertNotes(contentValues, vcard);
convertPhotos(contentValues, vcard);
convertOrganization(contentValues, vcard);
ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(contentValues.size());
ContentValues cv = account.getContentValues();
//ContactsContract.RawContact.CONTENT_URI needed to add account, backReference is also not needed
ContentProviderOperation operation =
ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValues(cv)
.build();
operations.add(operation);
for (NonEmptyContentValues values : contentValues) {
cv = values.getContentValues();
if (cv.size() == 0) {
continue;
}
//@formatter:off
operation =
ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValues(cv)
.build();
//@formatter:on
operations.add(operation);
}
// Executing all the insert operations as a single database transaction
context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, operations);
}
/**
* Save this model to the database within the given transaction.
* If this model has an @AutoIncrement annotation on a property
* than that property will be set when this method returns.
*
* @param t
* The transaction to save this model in
*
* @return whether or not the save was successful.
*/
final public boolean save(Transaction t) {
if (!isValid()) {
return false;
}
boolean doesExist = exists();
if (!doesExist) {
beforeCreate();
}
beforeSave();
final ContentValues cv = Utils.getContentValues(this);
if (cv.size() == 0) {
throw new ContentValuesEmptyException();
}
final String tableName = Utils.getTableName(getClass());
if (doesExist) {
if (t.update(tableName, cv, Utils.getWhereStatement(this)) == 0) {
return false;
}
} else {
long id = t.insert(tableName, cv);
if (id == -1) {
return false;
}
// set the @AutoIncrement column if one exists
final ModelInfo info = ModelInfo.from(getClass());
if (info.autoIncrementField != null) {
info.autoIncrementField.field.setAccessible(true);
try {
info.autoIncrementField.field.set(this, id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
t.addOnTransactionCommittedListener(new OnTransactionCommittedListener() {
@Override
public void onTransactionCommitted() {
Sprinkles.sInstance.mContext.getContentResolver().notifyChange(
Utils.getNotificationUri(Model.this.getClass()), null, true);
}
});
return true;
}
/**
* Convenience method for updating rows in the database.
*
* @param table the table to update in
* @param values a map from column names to new column values. null is a
* valid value that will be translated to NULL.
* @param whereClause the optional WHERE clause to apply when updating.
* Passing null will update all rows.
* @param whereArgs You may include ?s in the where clause, which
* will be replaced by the values from whereArgs. The values
* will be bound as Strings.
* @param conflictAlgorithm for update conflict resolver
* @return the number of rows affected
*/
public int updateWithOnConflict(String table, ContentValues values,
String whereClause, String[] whereArgs, int conflictAlgorithm) {
if (values == null || values.size() == 0) {
throw new IllegalArgumentException("Empty values");
}
acquireReference();
try {
StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE ");
sql.append(CONFLICT_VALUES[conflictAlgorithm]);
sql.append(table);
sql.append(" SET ");
// move all bind args to one array
int setValuesSize = values.size();
int bindArgsSize = (whereArgs == null) ? setValuesSize : (setValuesSize + whereArgs.length);
Object[] bindArgs = new Object[bindArgsSize];
int i = 0;
for (String colName : values.keySet()) {
sql.append((i > 0) ? "," : "");
sql.append(colName);
bindArgs[i++] = values.get(colName);
sql.append("=?");
}
if (whereArgs != null) {
for (i = setValuesSize; i < bindArgsSize; i++) {
bindArgs[i] = whereArgs[i - setValuesSize];
}
}
if (!TextUtils.isEmpty(whereClause)) {
sql.append(" WHERE ");
sql.append(whereClause);
}
SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
try {
return statement.executeUpdateDelete();
} finally {
statement.close();
}
} finally {
releaseReference();
}
}
/**
* A message was received and stored. Update topic record with the message info
*
* @return true on success, false otherwise
*/
@SuppressWarnings("WeakerAccess")
public static boolean msgReceived(SQLiteDatabase db, Topic topic, Date timestamp, int seq) {
StoredTopic st = (StoredTopic) topic.getLocal();
if (st == null) {
return false;
}
// Convert topic description to a map of values
ContentValues values = new ContentValues();
if (seq > st.maxLocalSeq) {
values.put(COLUMN_NAME_MAX_LOCAL_SEQ, seq);
values.put(COLUMN_NAME_RECV, seq);
}
if (seq > 0 && (st.minLocalSeq == 0 || seq < st.minLocalSeq)) {
values.put(COLUMN_NAME_MIN_LOCAL_SEQ, seq);
}
if (seq > topic.getSeq()) {
values.put(COLUMN_NAME_SEQ, seq);
}
if (timestamp.after(st.lastUsed)) {
values.put(COLUMN_NAME_LASTUSED, timestamp.getTime());
}
if (values.size() > 0) {
int updated = db.update(TABLE_NAME, values, _ID + "=" + st.id, null);
if (updated <= 0) {
return false;
}
st.lastUsed = timestamp.after(st.lastUsed) ? timestamp : st.lastUsed;
st.minLocalSeq = seq > 0 && (st.minLocalSeq == 0 || seq < st.minLocalSeq) ?
seq : st.minLocalSeq;
st.maxLocalSeq = Math.max(seq, st.maxLocalSeq);
}
return true;
}
/**
* Calling
* {@link android.database.sqlite.SQLiteDatabase#update(String, android.content.ContentValues, String, String[])} to
* update the current model.
*
* @param baseObj
* Current model to update.
* @param values
* To store data of current model for updating.
*/
private void updating(LitePalSupport baseObj, ContentValues values) {
if (values.size() > 0) {
mDatabase.update(baseObj.getTableName(), values, "id = ?",
new String[] { String.valueOf(baseObj.getBaseObjId()) });
}
}
/**
* The open interface for other classes in CRUD package to update. Using
* modelClass to decide which table to update, and id to decide a specific
* row. The value that need to update is stored in ContentValues.
*
* @param modelClass
* Which table to update by class.
* @param id
* Which record to update.
* @param values
* A map from column names to new column values. null is a valid
* value that will be translated to NULL.
* @return The number of rows affected.
*/
public int onUpdate(Class<?> modelClass, long id, ContentValues values) {
if (values.size() > 0) {
convertContentValues(values);
return mDatabase.update(getTableName(modelClass), values, "id = " + id, null);
}
return 0;
}