下面列出了怎么用android.content.ContentValues的API类实例代码及写法,或者点击链接到github查看源代码。
public String updateCourse(Courses aCore) {
open();
String msg = "Sorry!! Error for Updating";
try {
ContentValues cv = new ContentValues();
cv.put(DBOpenHelper.COURS_CODE, aCore.getcCode());
cv.put(DBOpenHelper.COURS_NAME, aCore.getcName());
cv.put(DBOpenHelper.COURS_DEPT, aCore.getdCode());
sqLiteDB.update(DBOpenHelper.TABLE_COURS, cv, " "
+ DBOpenHelper.COURS_CODE + "=" + "'" + aCore.getcCode()
+ "'", null);
msg = "Successfully Updated with: " + aCore.getcCode();
} catch (Exception e) {
msg = "Sorry!! Error for Updating with: " + aCore.getcCode();
}
close();
return msg;
}
private void updateDataDb(List<GankItem> gankItemList, String day) {
if (gankItemList == null || gankItemList.size() == 0) {
Log.d(TAG, "updateDataDb return for no data");
return;
}
for (GankItem gankItem: gankItemList) {
ContentValues item = new ContentValues();
item.put(GankDbHelper.Contract.COLUMN_ID, gankItem.id);
item.put(GankDbHelper.Contract.COLUMN_CATEGORY, gankItem.type);
item.put(GankDbHelper.Contract.COLUMN_DEST, gankItem.desc);
item.put(GankDbHelper.Contract.COLUMN_DAY, day);
item.put(GankDbHelper.Contract.COLUMN_URL, gankItem.url);
item.put(GankDbHelper.Contract.COLUMN_WHO, gankItem.who);
item.put(GankDbHelper.Contract.COLUMN_IMAGE, gankItem.getImage());
item.put(GankDbHelper.Contract.COLUMN_LIKE, gankItem.like ? 1 : 0);
sqLiteDatabase.insert(GankDbHelper.Contract.TABLE_DATA, null, item);
}
}
@Override
public void rotate(int degrees) throws Exception {
GalleryUtils.assertNotInRenderThread();
Uri baseUri = Images.Media.EXTERNAL_CONTENT_URI;
ContentValues values = new ContentValues();
int rotation = (this.rotation + degrees) % 360;
if (rotation < 0) rotation += 360;
if (mimeType.equalsIgnoreCase("image/jpeg")) {
ExifInterface exifInterface = new ExifInterface(filePath);
exifInterface.setAttribute(ExifInterface.TAG_ORIENTATION,
String.valueOf(rotation));
exifInterface.saveAttributes();
fileSize = new File(filePath).length();
values.put(Images.Media.SIZE, fileSize);
}
values.put(Images.Media.ORIENTATION, rotation);
mApplication.getContentResolver().update(baseUri, values, "_id=?",
new String[]{String.valueOf(id)});
}
void verifyBehaviorForMultipleContentValues(@Nullable PutResults<ContentValues> putResults) {
assertThat(putResults).isNotNull();
// only one call to storIOSQLite.put() should occur
verify(storIOSQLite).put();
// number of calls to putResolver's performPut() should be equal to number of objects
verify(putResolver, times(contentValues.size())).performPut(eq(storIOSQLite), any(ContentValues.class));
// each item should be "put"
for (final ContentValues cv : contentValues) {
verify(putResolver).performPut(storIOSQLite, cv);
}
verifyNotificationsAndTransactionBehavior();
}
public void insertIntoDb(String username, Bitmap image){
SQLiteDatabase db = this.getWritableDatabase();
if(hasObject(username, DB_TABLE))
deleteRow(username, DB_TABLE);
try {
ContentValues contentValues = new ContentValues();
contentValues.put(USERNAME, username);
contentValues.put(IMAGE_THUMBNAIL, ZoomstaUtil.getBytes(image));
db.insert(DB_TABLE, null, contentValues);
db.close();
} catch (SQLiteException e){
e.printStackTrace();
}
}
@Override
public void setGroupChatSubject(String subject) throws RemoteException {
try {
if (isGroupChatSession()) {
ChatGroup group = (ChatGroup)mChatSession.getParticipant();
getGroupManager().setGroupSubject(group, subject);
//update the database
ContentValues values1 = new ContentValues(1);
values1.put(Imps.Contacts.NICKNAME,subject);
ContentValues values = values1;
Uri uriContact = ContentUris.withAppendedId(Imps.Contacts.CONTENT_URI, mContactId);
mContentResolver.update(uriContact, values, null, null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveState() {
String category = (String) mCategory.getSelectedItem();
String summary = mTitleText.getText().toString();
String description = mBodyText.getText().toString();
// Only save if either summary or description
// is available
if (description.length() == 0 && summary.length() == 0) {
return;
}
ContentValues values = new ContentValues();
values.put(TodoTable.COLUMN_CATEGORY, category);
values.put(TodoTable.COLUMN_SUMMARY, summary);
values.put(TodoTable.COLUMN_DESCRIPTION, description);
if (todoUri == null) {
// New todo
todoUri = getContentResolver().insert(
MyTodoContentProvider.CONTENT_URI, values);
} else {
// Update todo
getContentResolver().update(todoUri, values, null, null);
}
}
private static synchronized long getAppKey(SQLiteDatabase db, String packageName, String signatureDigest) {
Cursor cursor = db.rawQuery("SELECT _id FROM appkeys WHERE packageName=? AND signatureDigest=?", new String[]{packageName, signatureDigest});
if (cursor != null) {
try {
if (cursor.moveToNext()) {
return cursor.getLong(0);
}
} finally {
cursor.close();
}
}
ContentValues appKey = new ContentValues();
appKey.put("packageName", packageName);
appKey.put("signatureDigest", signatureDigest);
return db.insert("appkeys", null, appKey);
}
public DatabaseHelper updateSteps(long id, long time, int value) {
synchronized (mContext.getApplicationContext()) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("count", value);
if (db.update("step", cv, "ID = ?", new String[]{Long.toString(id)}) != 1)
Log.e(TAG, "Update step failed");
}
for (StepCountChangedListener listener : mStepCountChangedListeners)
try {
listener.onStepCountUpdated(time, value);
} catch (Throwable ex) {
Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
}
return this;
}
/**
* Method that handles bulk insert requests. This method plays
* the role of the "template method" in the Template Method
* pattern.
*/
public int bulkInsert(Uri uri,
ContentValues[] cvsArray) {
// Try to match against the path in a url. It returns the
// code for the matched node (added using addURI), or -1 if
// there is no matched node. If there's a match insert new
// rows.
switch (sUriMatcher.match(uri)) {
case CHARACTERS:
int returnCount = bulkInsertCharacters(uri,
cvsArray);
if (returnCount > 0)
// Notifies registered observers that row(s) were
// inserted.
mContext.getContentResolver().notifyChange(uri,
null);
return returnCount;
default:
throw new UnsupportedOperationException();
}
}
private void updateFilesTableAccordingToShareInsertion(
SQLiteDatabase db, ContentValues newShare
) {
ContentValues fileValues = new ContentValues();
int newShareType = newShare.getAsInteger(ProviderTableMeta.OCSHARES_SHARE_TYPE);
if (newShareType == ShareType.PUBLIC_LINK.getValue()) {
fileValues.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, 1);
} else if (
newShareType == ShareType.USER.getValue() ||
newShareType == ShareType.GROUP.getValue() ||
newShareType == ShareType.FEDERATED.getValue() ) {
fileValues.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, 1);
}
String where = ProviderTableMeta.FILE_PATH + "=? AND " +
ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?";
String[] whereArgs = new String[] {
newShare.getAsString(ProviderTableMeta.OCSHARES_PATH),
newShare.getAsString(ProviderTableMeta.OCSHARES_ACCOUNT_OWNER)
};
db.update(ProviderTableMeta.FILE_TABLE_NAME, fileValues, where, whereArgs);
}
public ContentValues toContentValues() {
ContentValues contentValues = new ContentValues();
contentValues.put("sourceNode", source);
contentValues.put("seqId", seqId);
contentValues.put("v1SourceNode", source);
contentValues.put("v1SeqId", v1SeqId);
contentValues.put("timestampMs", lastModified);
if (deleted) {
contentValues.put("deleted", 1);
contentValues.putNull("data");
} else {
contentValues.put("deleted", 0);
contentValues.put("data", dataItem.data);
}
contentValues.put("assetsPresent", assetsAreReady ? 1 : 0);
return contentValues;
}
/**
* Creates new logger session. Must be created before appending log entries.
* If the nRF Logger application is not installed the method will return <code>null</code>.
*
* @param context
* the context (activity, service or application)
* @param authority
* the {@link LocalLogContentProvider} authority
* @param key
* the session key, which is used to group sessions
* @param name
* the human readable session name
* @return the {@link LogContract} that can be used to append log entries or <code>null</code>
* if MCP is not installed. The <code>null</code> value can be next passed to logging methods
*/
public static LocalLogSession newSession(@NonNull final Context context,
@NonNull final Uri authority,
@NonNull final String key, @NonNull final String name) {
final Uri uri = authority.buildUpon()
.appendEncodedPath(LogContract.Session.SESSION_CONTENT_DIRECTORY)
.appendEncodedPath(LogContract.Session.KEY_CONTENT_DIRECTORY)
.appendEncodedPath(key)
.build();
final ContentValues values = new ContentValues();
values.put(LogContract.Session.NAME, name);
try {
final Uri sessionUri = context.getContentResolver().insert(uri, values);
if (sessionUri != null)
return new LocalLogSession(context, sessionUri);
return null;
} catch (final Exception e) {
Log.e("LocalLogSession", "Error while creating a local log session.", e);
return null;
}
}
/**
* 保存数据到数据库<br />
* <b>注意:</b><br />
* 保存成功后,entity的主键将被赋值(或更新)为数据库的主键, 只针对自增长的id有效
*
* @param entity
* 要保存的数据
* @return ture: 保存成功 false:保存失败
*/
public boolean saveBindId(Object entity) {
checkTableExist(entity.getClass());
List<KeyValue> entityKvList = SqlBuilder
.getSaveKeyValueListByEntity(entity);
if (entityKvList != null && entityKvList.size() > 0) {
TableInfo tf = TableInfo.get(entity.getClass());
ContentValues cv = new ContentValues();
insertContentValues(entityKvList, cv);
Long id = db.insert(tf.getTableName(), null, cv);
if (id == -1)
return false;
tf.getId().setValue(entity, id);
return true;
}
return false;
}
/**
* 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;
}
private void finalizeSyncProducts() {
/*
NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(0);
*/
ContentValues[] productsValuesArray = new ContentValues[productsValues.size()];
productsValuesArray = productsValues.toArray(productsValuesArray);
int ordersRowsUpdated = getContext().getContentResolver().bulkInsert(WoodminContract.ProductEntry.CONTENT_URI, productsValuesArray);
Log.v(LOG_TAG, "Products " + ordersRowsUpdated + " updated");
/*
String query = WoodminContract.ProductEntry.COLUMN_ENABLE + " = ?" ;
String[] parameters = new String[]{ String.valueOf("0") };
int rowsDeleted = getContext().getContentResolver().delete(WoodminContract.ProductEntry.CONTENT_URI,
query,
parameters);
Log.d(LOG_TAG, "Products: " + rowsDeleted + " old records deleted.");
*/
getContext().getContentResolver().notifyChange(WoodminContract.ProductEntry.CONTENT_URI, null, false);
pageProduct = 0;
}
public static void update(GroupListBean bean, String accountId) {
if (bean == null || bean.getLists().size() == 0) {
return;
}
clearGroup(accountId);
ContentValues cv = new ContentValues();
cv.put(GroupTable.ACCOUNTID, accountId);
cv.put(GroupTable.JSONDATA, new Gson().toJson(bean));
getWsd().insert(GroupTable.TABLE_NAME, HomeTable.ID, cv);
}
private static void insertDrink(SQLiteDatabase db, String name,
String description, int resourceId) {
ContentValues drinkValues = new ContentValues();
drinkValues.put("NAME", name);
drinkValues.put("DESCRIPTION", description);
drinkValues.put("IMAGE_RESOURCE_ID", resourceId);
db.insert("DRINK", null, drinkValues);
}
public static ContentValues addSyncDataToCV(ContentValues values, BaseModel baseModel) {
values.put(DBHelper.C_SYNC_FBID, baseModel.getFBID());
values.put(DBHelper.C_SYNC_TS, baseModel.getTS());
values.put(DBHelper.C_SYNC_DELETED, 0);
values.put(DBHelper.C_SYNC_DIRTY, baseModel.isDirty() ? 1 : 0);
values.put(DBHelper.C_SYNC_LASTEDITED, baseModel.getLastEdited());
return values;
}
private ContentValues getContentValues(ComponentName componentName, int badgeCount, boolean isInsert) {
ContentValues contentValues = new ContentValues();
if (isInsert) {
contentValues.put("package", componentName.getPackageName());
contentValues.put("class", componentName.getClassName());
}
contentValues.put("badgecount", badgeCount);
return contentValues;
}
@Override
public ContentValues toContentValues() {
ContentValues values = new ContentValues();
values.put(UID, this.uid);
values.put(NAME, this.name);
values.put(DOMAIN, this.domain);
values.put(HTTPS, this.https);
values.put(SOFTWARE, this.software);
values.put(BOARD, this.board);
values.put(REPORTS, this.reports);
return values;
}
private ContentValues getOrganizationTypeCV(Organization organization, int id) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, id);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.Data.DATA1, organization.getName());
contentValues.put(ContactsContract.Data.DATA4, organization.getTitle());
return contentValues;
}
public static void writeDBStorage(String deviceID, ContentValues newValues)
{
String tableName = SQLTableName.PREFIX + deviceID + SQLTableName.GYROSCOPE;
if(Settings.DATABASE_DIRECT_INSERT) {
SQLDBController.getInstance().insert(tableName, null, newValues);
return;
}
List<String[]> clone = DBUtils.manageCache(deviceID, cache, newValues, (Settings.DATABASE_CACHE_SIZE + type * 200));
if(clone != null) {
SQLDBController.getInstance().bulkInsert(tableName, clone);
}
}
public boolean insert_2_homeposts(String id, String smallicon, String title, String body, String bigpicture, String largeicon, String launchurl) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NOTIFICATION_ID, id);
contentValues.put(NOTIFICATION_small_icon, smallicon);
contentValues.put(NOTIFICATION_TITLE, title);
contentValues.put(NOTIFICATION_BODY, body);
contentValues.put(NOTIFICATION_BIG_PICTURE, bigpicture);
contentValues.put(NOTIFICATION_LARGE_ICON, largeicon);
contentValues.put(NOTIFICATION_LAUNCH_URL, launchurl);
db.insert(TABLE_HOMEPOST, null, contentValues);
return true;
}
static private int getDownloadManagerPendingIdFromWordlistId(final Context context,
final String clientId, final String wordlistId) {
final SQLiteDatabase db = MetadataDbHelper.getDb(context, clientId);
final ContentValues wordlistValues =
MetadataDbHelper.getContentValuesOfLatestAvailableWordlistById(db, wordlistId);
if (null == wordlistValues) {
// We don't know anything about a word list with this id. Bug? This should never
// happen, but still return to prevent a crash.
Log.e(TAG, "Unexpected word list ID: " + wordlistId);
return NOT_A_DOWNLOADMANAGER_PENDING_ID;
}
return wordlistValues.getAsInteger(MetadataDbHelper.PENDINGID_COLUMN);
}
public static OAuthActivity.DBResult updateAccountHackToken(AccountBean account, String toaken_hack, long token_hack_exp) {
ContentValues cv = new ContentValues();
cv.put(AccountTable.ACCESS_TOKEN_HACK, toaken_hack);
// toaken_time
cv.put(AccountTable.ACCESS_TOKEN_HACK_EXPIRES_TIME, token_hack_exp);
String[] args = {
account.getUid()
};
getWsd().update(AccountTable.ACCOUNT_TABLE, cv, AccountTable.UID + "=?", args);
return OAuthActivity.DBResult.update_successfully;
}
/**
* Updating data is not supported, and will throw an exception.
* @see ContentProvider#update(Uri, ContentValues, String, String[])
* @see ContentProvider#insert(Uri, ContentValues)
*/
@Override
public int update(final Uri uri, final ContentValues values, final String selection,
final String[] selectionArgs) throws UnsupportedOperationException {
PrivateLog.log("Attempt to update : " + uri);
throw new UnsupportedOperationException("Updating dictionary words is not supported");
}
@Override
public int bulkInsert(final Uri uri, final ContentValues[] values) {
final SQLiteDatabase database = getDatabase();
if (database != null) {
return insertWithTransaction(database, getName(), values);
} else {
throw new IllegalStateException("Database is null.");
}
}
/**
* Handle updating data.
*/
@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count;
String finalWhere;
switch (mUriMatcher.match(uri)) {
case MAIN:
// If URI is main table, update uses incoming where clause and args.
count = db.update(MainTable.TABLE_NAME, values, where, whereArgs);
break;
case MAIN_ID:
// If URI is for a particular row ID, update is based on incoming
// data but modified to restrict to the given ID.
finalWhere = DatabaseUtilsCompat.concatenateWhere(
MainTable._ID + " = " + ContentUris.parseId(uri), where);
count = db.update(MainTable.TABLE_NAME, values, finalWhere, whereArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
static void updateCount(String msgId, int commentCount, int repostCount) {
String sql = "select * from " + HomeOtherGroupTable.HomeOtherGroupDataTable.TABLE_NAME + " where "
+ HomeOtherGroupTable.HomeOtherGroupDataTable.MBLOGID + " = " + msgId + " order by "
+ HomeOtherGroupTable.HomeOtherGroupDataTable.ID
+ " asc limit 50";
Cursor c = getRsd().rawQuery(sql, null);
Gson gson = new Gson();
while (c.moveToNext()) {
String id = c.getString(c.getColumnIndex(HomeOtherGroupTable.HomeOtherGroupDataTable.ID));
String json = c.getString(c.getColumnIndex(HomeOtherGroupTable.HomeOtherGroupDataTable.JSONDATA));
if (!TextUtils.isEmpty(json)) {
try {
MessageBean value = gson.fromJson(json, MessageBean.class);
value.setComments_count(commentCount);
value.setReposts_count(repostCount);
String[] args = {
id
};
ContentValues cv = new ContentValues();
cv.put(HomeOtherGroupTable.HomeOtherGroupDataTable.JSONDATA, gson.toJson(value));
getWsd().update(HomeOtherGroupTable.HomeOtherGroupDataTable.TABLE_NAME, cv,
HomeOtherGroupTable.HomeOtherGroupDataTable.ID + "=?", args);
} catch (JsonSyntaxException e) {
}
}
}
}