下面列出了android.content.ContentValues#putNull ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void resetUsage(int uid) {
lock.writeLock().lock();
try {
// There is a segmented index on uid
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransactionNonExclusive();
try {
ContentValues cv = new ContentValues();
cv.putNull("sent");
cv.putNull("received");
cv.putNull("connections");
db.update("access", cv,
(uid < 0 ? null : "uid = ?"),
(uid < 0 ? null : new String[]{Integer.toString(uid)}));
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} finally {
lock.writeLock().unlock();
}
notifyAccessChanged();
}
/**
* Creates an operation to delete a preference. All fields
* are pre-filled. This will also add the values to the
* operation queue.
*
* @param key The preference key to delete.
* @return The pre-filled values.
*/
private ContentValues createRemoveOp(String key) {
// Note: Remove operations are inserted at the beginning
// of the list (this preserves the SharedPreferences behavior
// that all removes are performed before any adds)
ContentValues values = createContentValues(key, RemoteContract.TYPE_NULL);
values.putNull(RemoteContract.COLUMN_VALUE);
mValues.add(0, values);
return values;
}
public DatabaseHelper updateLocationName(long id, String name) {
synchronized (mContext.getApplicationContext()) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("name", name);
cv.putNull("sent");
if (db.update("location", cv, "ID = ?", new String[]{Long.toString(id)}) != 1)
Log.e(TAG, "Update location failed");
}
notifyLocationUpdated(id);
return this;
}
@Override
public void setIn(ContentValues values, Float value)
{
if (value != null)
{
values.put(mFieldName, value);
}
else
{
values.putNull(mFieldName);
}
}
@Override
public void setIn(ContentValues values, Long value)
{
if (value != null)
{
values.put(mFieldName, value);
}
else
{
values.putNull(mFieldName);
}
}
public DatabaseHelper updateLocationTime(long id, long time) {
synchronized (mContext.getApplicationContext()) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("time", time);
cv.putNull("sent");
if (db.update("location", cv, "ID = ?", new String[]{Long.toString(id)}) != 1)
Log.e(TAG, "Update location failed");
}
notifyLocationUpdated(id);
return this;
}
public void addPerson(String name, Uri lookup, int itemsOnLoan, int itemsLoaned){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PEOPLE_ITEMSLOANED, itemsLoaned);
values.put(PEOPLE_ITEMSONLOAN, itemsOnLoan);
if(lookup!=null){
values.put(PEOPLE_LOOKUPURI, lookup.toString());
} else {
values.putNull(PEOPLE_LOOKUPURI);
}
values.put(PEOPLE_NAME, name);
db.insert(PEOPLE_TABLENAME, null, values);
db.close();
}
@Override
public void setIn(ContentValues values, RecurrenceRule value)
{
if (value != null)
{
values.put(mFieldName, value.toString());
}
else
{
values.putNull(mFieldName);
}
}
private void nullifyOrderOfCollecion(int collectionsId) {
ContentValues contentValues = new ContentValues();
contentValues.putNull(UserDataDBContract.BooksCollectionEntry.COLUMN_ORDER);
getWritableDatabase().update(UserDataDBContract.BooksCollectionEntry.Table_NAME,
contentValues, UserDataDBContract.BooksCollectionEntry.COLUMN_ID + "=?",
new String[]{String.valueOf(collectionsId)}
);
}
@Override
public void setIn(ContentValues values, Long value)
{
if (value != null)
{
values.put(mFieldName, value);
}
else
{
values.putNull(mFieldName);
}
}
@Test
public void testGetFromCVFloating1()
{
ContentValues values = new ContentValues();
FieldAdapter<Iterable<DateTime>, ?> adapter = new DateTimeIterableFieldAdapter<TaskAdapter>("x", "y");
values.put("x", "20180109T140000");
values.putNull("y");
assertThat(adapter.getFrom(values), iteratesTo(DateTime.parse("20180109T140000")));
}
@Override
public void setIn(ContentValues values, URI value)
{
if (value != null)
{
values.put(mFieldName, value.toASCIIString());
}
else
{
values.putNull(mFieldName);
}
}
@Override
public void onReceive(Context context, Intent intent) {
Uri data = intent.getData();
if(data == null) {
Log.e("DeleteNoteReceiver", "Could not delete note: uri is null");
return;
}
/*
* For some reason I forgot the pins must not be deleted from the database right away.
* I think it had something to do with the _id value in the database which is needed to reference visible notifications.
* So we still need it in order to hide the deleted pins.
*
* The deleted pins are cleaned up on every boot (if the system allows us to catch the boot completed intent. For more information see BootReceiver)
*/
ContentValues cv = new ContentValues();
cv.putNull(NotesProvider.Notes.TEXT);//setting text to NULL marks note as deleted, it will be removed at next boot
cv.put(NotesProvider.Notes.MODIFIED, System.currentTimeMillis());
switch(mUris.match(data)) {
case NOTES_ITEM:
//Check if last path segment is really just a valid id (probably redundant)
String idstring = data.getLastPathSegment();
if(TextUtils.isEmpty(idstring) || !TextUtils.isDigitsOnly(idstring)) {
Log.e("DeleteNoteReceiver", String.format("Could not delete note item: invalid id '%s' in uri '%s'", idstring, data.toString()));
return;
}
//continue to next
case NOTES_LIST:
int rows = context.getContentResolver().update(data, cv, "text IS NOT NULL", null);//delete either on note item or all notes which are not marked as deleted already (text is not null)
Log.d("DeleteNoteProvider", String.format("Deleted %d rows", rows));
//update notifications
//context.startService(new Intent(context, PinboardService.class));
Pinboard.get(context).updateAll(true);
return;
default:
Log.e("DeleteNoteReceiver", String.format("Could not snooze note: invalid uri '%s'", data.toString()));
return;
}
}
/**
>>>>>>> a6840f1... S07.03-Exercise-ConflictResolutionPolicy
* Tests the columns with null values cannot be inserted into the database.
*/
@Test
public void testNullColumnConstraints() {
/* Use a WeatherDbHelper to get access to a writable database */
/* We need a cursor from a weather table query to access the column names */
Cursor weatherTableCursor = database.query(
REFLECTED_TABLE_NAME,
/* We don't care about specifications, we just want the column names */
null, null, null, null, null, null);
/* Store the column names and close the cursor */
String[] weatherTableColumnNames = weatherTableCursor.getColumnNames();
weatherTableCursor.close();
/* Obtain weather values from TestUtilities and make a copy to avoid altering singleton */
ContentValues testValues = TestUtilities.createTestWeatherContentValues();
/* Create a copy of the testValues to save as a reference point to restore values */
ContentValues testValuesReferenceCopy = new ContentValues(testValues);
for (String columnName : weatherTableColumnNames) {
/* We don't need to verify the _ID column value is not null, the system does */
if (columnName.equals(WeatherContract.WeatherEntry._ID)) continue;
/* Set the value to null */
testValues.putNull(columnName);
/* Insert ContentValues into database and get a row ID back */
long shouldFailRowId = database.insert(
REFLECTED_TABLE_NAME,
null,
testValues);
String variableName = getConstantNameByStringValue(
WeatherContract.WeatherEntry.class,
columnName);
/* If the insert fails, which it should in this case, database.insert returns -1 */
String nullRowInsertShouldFail =
"Insert should have failed due to a null value for column: '" + columnName + "'"
+ ", but didn't."
+ "\n Check that you've added NOT NULL to " + variableName
+ " in your create table statement in the WeatherEntry class."
+ "\n Row ID: ";
assertEquals(nullRowInsertShouldFail,
-1,
shouldFailRowId);
/* "Restore" the original value in testValues */
testValues.put(columnName, testValuesReferenceCopy.getAsDouble(columnName));
}
/* Close database */
dbHelper.close();
}
/**
>>>>>>> a6840f1... S07.03-Exercise-ConflictResolutionPolicy
* Tests the columns with null values cannot be inserted into the database.
*/
@Test
public void testNullColumnConstraints() {
/* Use a WeatherDbHelper to get access to a writable database */
/* We need a cursor from a weather table query to access the column names */
Cursor weatherTableCursor = database.query(
REFLECTED_TABLE_NAME,
/* We don't care about specifications, we just want the column names */
null, null, null, null, null, null);
/* Store the column names and close the cursor */
String[] weatherTableColumnNames = weatherTableCursor.getColumnNames();
weatherTableCursor.close();
/* Obtain weather values from TestUtilities and make a copy to avoid altering singleton */
ContentValues testValues = TestUtilities.createTestWeatherContentValues();
/* Create a copy of the testValues to save as a reference point to restore values */
ContentValues testValuesReferenceCopy = new ContentValues(testValues);
for (String columnName : weatherTableColumnNames) {
/* We don't need to verify the _ID column value is not null, the system does */
if (columnName.equals(WeatherContract.WeatherEntry._ID)) continue;
/* Set the value to null */
testValues.putNull(columnName);
/* Insert ContentValues into database and get a row ID back */
long shouldFailRowId = database.insert(
REFLECTED_TABLE_NAME,
null,
testValues);
String variableName = getConstantNameByStringValue(
WeatherContract.WeatherEntry.class,
columnName);
/* If the insert fails, which it should in this case, database.insert returns -1 */
String nullRowInsertShouldFail =
"Insert should have failed due to a null value for column: '" + columnName + "'"
+ ", but didn't."
+ "\n Check that you've added NOT NULL to " + variableName
+ " in your create table statement in the WeatherEntry class."
+ "\n Row ID: ";
assertEquals(nullRowInsertShouldFail,
-1,
shouldFailRowId);
/* "Restore" the original value in testValues */
testValues.put(columnName, testValuesReferenceCopy.getAsDouble(columnName));
}
/* Close database */
dbHelper.close();
}
public void insertLog(Packet packet, String dname, int connection, boolean interactive) {
lock.writeLock().lock();
try {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransactionNonExclusive();
try {
ContentValues cv = new ContentValues();
cv.put("time", packet.time);
cv.put("version", packet.version);
if (packet.protocol < 0)
cv.putNull("protocol");
else
cv.put("protocol", packet.protocol);
cv.put("flags", packet.flags);
cv.put("saddr", packet.saddr);
if (packet.sport < 0)
cv.putNull("sport");
else
cv.put("sport", packet.sport);
cv.put("daddr", packet.daddr);
if (packet.dport < 0)
cv.putNull("dport");
else
cv.put("dport", packet.dport);
if (dname == null)
cv.putNull("dname");
else
cv.put("dname", dname);
cv.put("data", packet.data);
if (packet.uid < 0)
cv.putNull("uid");
else
cv.put("uid", packet.uid);
cv.put("allowed", packet.allowed ? 1 : 0);
cv.put("connection", connection);
cv.put("interactive", interactive ? 1 : 0);
if (db.insert("log", null, cv) == -1)
Log.e(TAG, "Insert log failed");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} finally {
lock.writeLock().unlock();
}
notifyLogChanged();
}
@Override
public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion)
{
/*
* Delete all sessions in the database, in order to get the data back into a consistent state. This is necessary
* because an Android bug that caused the database in older versions of the Localytics library to become corrupted.
*/
if (oldVersion < 3)
{
db.delete(UploadBlobEventsDbColumns.TABLE_NAME, null, null);
db.delete(EventHistoryDbColumns.TABLE_NAME, null, null);
db.delete(UploadBlobsDbColumns.TABLE_NAME, null, null);
db.delete(AttributesDbColumns.TABLE_NAME, null, null);
db.delete(EventsDbColumns.TABLE_NAME, null, null);
db.delete(SessionsDbColumns.TABLE_NAME, null, null);
}
if (oldVersion < 4)
{
// if the table is upgraded, it won't have the NOT NULL constraint that is normally present when the table is
// freshly created
db.execSQL(String.format("ALTER TABLE %s ADD COLUMN %s TEXT;", SessionsDbColumns.TABLE_NAME, SessionsDbColumns.LOCALYTICS_INSTALLATION_ID)); //$NON-NLS-1$
}
if (oldVersion < 5)
{
db.execSQL(String.format("ALTER TABLE %s ADD COLUMN %s TEXT;", SessionsDbColumns.TABLE_NAME, SessionsDbColumns.DEVICE_WIFI_MAC_HASH)); //$NON-NLS-1$
}
if (oldVersion < 6)
{
Cursor attributesCursor = null;
try
{
attributesCursor = db.query(AttributesDbColumns.TABLE_NAME, new String[]
{
AttributesDbColumns._ID,
AttributesDbColumns.ATTRIBUTE_KEY }, null, null, null, null, null);
final int idColumnIndex = attributesCursor.getColumnIndexOrThrow(AttributesDbColumns._ID);
final int keyColumnIndex = attributesCursor.getColumnIndexOrThrow(AttributesDbColumns.ATTRIBUTE_KEY);
final ContentValues tempValues = new ContentValues();
final String whereClause = String.format("%s = ?", AttributesDbColumns._ID); //$NON-NLS-1$
final String[] whereArgs = new String[1];
attributesCursor.moveToPosition(-1);
while (attributesCursor.moveToNext())
{
tempValues.put(AttributesDbColumns.ATTRIBUTE_KEY, String.format(AttributesDbColumns.ATTRIBUTE_FORMAT, mContext.getPackageName(), attributesCursor.getString(keyColumnIndex)));
whereArgs[0] = Long.toString(attributesCursor.getLong(idColumnIndex));
db.update(AttributesDbColumns.TABLE_NAME, tempValues, whereClause, whereArgs);
tempValues.clear();
}
}
finally
{
if (null != attributesCursor)
{
attributesCursor.close();
attributesCursor = null;
}
}
}
if (oldVersion < 7)
{
// info table
db.execSQL(String.format("CREATE TABLE %s (%s TEXT, %s INTEGER);", InfoDbColumns.TABLE_NAME, InfoDbColumns.FB_ATTRIBUTION, InfoDbColumns.FIRST_RUN));
final ContentValues values = new ContentValues();
values.putNull(InfoDbColumns.FB_ATTRIBUTION);
values.put(InfoDbColumns.FIRST_RUN, Boolean.FALSE);
db.insertOrThrow(InfoDbColumns.TABLE_NAME, null, values);
}
if (oldVersion < 8)
{
// identifiers table
db.execSQL(String.format("CREATE TABLE %s (%s INTEGER PRIMARY KEY AUTOINCREMENT, %s TEXT UNIQUE NOT NULL, %s TEXT NOT NULL);", IdentifiersDbColumns.TABLE_NAME, IdentifiersDbColumns._ID, IdentifiersDbColumns.KEY, IdentifiersDbColumns.VALUE));
// add primary key for information table
db.execSQL(String.format("ALTER TABLE %s ADD COLUMN %s INTEGER PRIMARY KEY AUTOINCREMENT;", InfoDbColumns.TABLE_NAME, InfoDbColumns._ID)); //$NON-NLS-1$
}
}
/**
>>>>>>> a6840f1... S07.03-Exercise-ConflictResolutionPolicy
* Tests the columns with null values cannot be inserted into the database.
*/
@Test
public void testNullColumnConstraints() {
/* Use a WeatherDbHelper to get access to a writable database */
/* We need a cursor from a weather table query to access the column names */
Cursor weatherTableCursor = database.query(
REFLECTED_TABLE_NAME,
/* We don't care about specifications, we just want the column names */
null, null, null, null, null, null);
/* Store the column names and close the cursor */
String[] weatherTableColumnNames = weatherTableCursor.getColumnNames();
weatherTableCursor.close();
/* Obtain weather values from TestUtilities and make a copy to avoid altering singleton */
ContentValues testValues = TestUtilities.createTestWeatherContentValues();
/* Create a copy of the testValues to save as a reference point to restore values */
ContentValues testValuesReferenceCopy = new ContentValues(testValues);
for (String columnName : weatherTableColumnNames) {
/* We don't need to verify the _ID column value is not null, the system does */
if (columnName.equals(WeatherContract.WeatherEntry._ID)) continue;
/* Set the value to null */
testValues.putNull(columnName);
/* Insert ContentValues into database and get a row ID back */
long shouldFailRowId = database.insert(
REFLECTED_TABLE_NAME,
null,
testValues);
String variableName = getConstantNameByStringValue(
WeatherContract.WeatherEntry.class,
columnName);
/* If the insert fails, which it should in this case, database.insert returns -1 */
String nullRowInsertShouldFail =
"Insert should have failed due to a null value for column: '" + columnName + "'"
+ ", but didn't."
+ "\n Check that you've added NOT NULL to " + variableName
+ " in your create table statement in the WeatherEntry class."
+ "\n Row ID: ";
assertEquals(nullRowInsertShouldFail,
-1,
shouldFailRowId);
/* "Restore" the original value in testValues */
testValues.put(columnName, testValuesReferenceCopy.getAsDouble(columnName));
}
/* Close database */
dbHelper.close();
}
private static Bundle initApp(Context context, Bundle extras) throws Throwable {
enforcePermission(context);
String packageName = extras.getString("packageName");
int uid = extras.getInt("uid");
boolean kill = extras.getBoolean("kill", false);
int userid = Util.getUserId(uid);
List<String> collection = getCollection(context, Util.getUserId(uid));
List<String> hookids = new ArrayList<>();
synchronized (lock) {
for (XHook hook : hooks.values())
if (hook.isAvailable(packageName, collection))
hookids.add(hook.getId());
}
dbLock.writeLock().lock();
try {
db.beginTransaction();
try {
for (String hookid : hookids) {
ContentValues cv = new ContentValues();
cv.put("package", packageName);
cv.put("uid", uid);
cv.put("hook", hookid);
cv.put("installed", -1);
cv.put("used", -1);
cv.put("restricted", 0);
cv.putNull("exception");
long rows = db.insertWithOnConflict("assignment", null, cv, SQLiteDatabase.CONFLICT_REPLACE);
if (rows < 0)
throw new Throwable("Error inserting assignment");
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} finally {
dbLock.writeLock().unlock();
}
if (kill)
forceStop(context, packageName, userid);
Log.i(TAG, "Init app pkg=" + packageName + " uid=" + uid + " assignments=" + hookids.size());
return new Bundle();
}
/**
* A method to createTrackedEntityAttribute ContentValues for a Program.
* To be used by other tests.
* @param id
* @param uid
* @param relatedProgram
* @param trackedEntityUid @return
*/
public static ContentValues create(long id, String uid,
String relatedProgram, @Nullable String trackedEntityUid) {
ContentValues program = new ContentValues();
program.put(Columns.ID, id);
program.put(Columns.UID, uid);
program.put(Columns.CODE, CODE);
program.put(Columns.NAME, NAME);
program.put(Columns.DISPLAY_NAME, DISPLAY_NAME);
program.put(Columns.CREATED, DATE);
program.put(Columns.LAST_UPDATED, DATE);
program.put(Columns.SHORT_NAME, SHORT_NAME);
program.put(Columns.DISPLAY_SHORT_NAME, DISPLAY_SHORT_NAME);
program.put(Columns.DESCRIPTION, DESCRIPTION);
program.put(Columns.DISPLAY_DESCRIPTION, DISPLAY_DESCRIPTION);
program.put(Columns.VERSION, VERSION);
program.put(Columns.ONLY_ENROLL_ONCE, ONLY_ENROLL_ONCE);
program.put(Columns.ENROLLMENT_DATE_LABEL, ENROLLMENT_DATE_LABEL);
program.put(Columns.DISPLAY_INCIDENT_DATE, DISPLAY_INCIDENT_DATE);
program.put(Columns.INCIDENT_DATE_LABEL, INCIDENT_DATE_LABEL);
program.put(Columns.REGISTRATION, REGISTRATION);
program.put(Columns.SELECT_ENROLLMENT_DATES_IN_FUTURE, SELECT_ENROLLMENT_DATES_IN_FUTURE);
program.put(Columns.DATA_ENTRY_METHOD, DATA_ENTRY_METHOD);
program.put(Columns.IGNORE_OVERDUE_EVENTS, IGNORE_OVERDUE_EVENTS);
program.put(Columns.SELECT_INCIDENT_DATES_IN_FUTURE, SELECT_INCIDENT_DATES_IN_FUTURE);
program.put(Columns.USE_FIRST_STAGE_DURING_REGISTRATION, USE_FIRST_STAGE_DURING_REGISTRATION);
program.put(Columns.DISPLAY_FRONT_PAGE_LIST, DISPLAY_FRONT_PAGE_LIST);
program.put(Columns.PROGRAM_TYPE, PROGRAM_TYPE.name());
if (relatedProgram == null) {
program.putNull(Columns.RELATED_PROGRAM);
} else {
program.put(Columns.RELATED_PROGRAM, RELATED_PROGRAM);
}
if(trackedEntityUid == null) {
program.putNull(Columns.TRACKED_ENTITY_TYPE);
} else {
program.put(Columns.TRACKED_ENTITY_TYPE, trackedEntityUid);
}
return program;
}