Java Code Examples for android.database.sqlite.SQLiteDatabase#insertWithOnConflict()

The following examples show how to use android.database.sqlite.SQLiteDatabase#insertWithOnConflict() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * Inserts NGrams relations for a task entry.
 * 
 * @param db
 *            A writable {@link SQLiteDatabase}.
 * @param ngramIds
 *            The set of NGram ids.
 * @param taskId
 *            The row id of the task.
 * @param propertyId
 *            The row id of the property.
 * @param The
 *            entry type of the relation (title, description, property).
 */
private static void insertNGramRelations(SQLiteDatabase db, Set<Long> ngramIds, long taskId, Long propertyId, int contentType)
{
	ContentValues values = new ContentValues(4);
	for (Long ngramId : ngramIds)
	{
		values.put(FTSContentColumns.TASK_ID, taskId);
		values.put(FTSContentColumns.NGRAM_ID, ngramId);
		values.put(FTSContentColumns.TYPE, contentType);
		if (contentType == SearchableTypes.PROPERTY)
		{
			values.put(FTSContentColumns.PROPERTY_ID, propertyId);
		}
		else
		{
			values.putNull(FTSContentColumns.PROPERTY_ID);
		}
		db.insertWithOnConflict(FTS_CONTENT_TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
	}

}
 
Example 2
Source Project: journaldev   File: FavouritesViewModel.java    License: MIT License 6 votes vote down vote up
public Favourites addFav(String url, long date) {

        Log.d("API123", "addFav " + url);

        SQLiteDatabase db = mFavHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DbSettings.DBEntry.COL_FAV_URL, url);
        values.put(DbSettings.DBEntry.COL_FAV_DATE, date);
        long id = db.insertWithOnConflict(DbSettings.DBEntry.TABLE,
                null,
                values,
                SQLiteDatabase.CONFLICT_REPLACE);
        db.close();
        Favourites fav = new Favourites(id, url, date);
        mFavs.add(fav);
        return new Favourites(fav);
    }
 
Example 3
public void putQuest(int key, String value, int type) {
    Date currentTime = getJapanCalendarInstance().getTime();
    SimpleDateFormat df = getJapanSimpleDataFormat("yy-MM-dd-HH");
    String time = df.format(currentTime);

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put("KEY", key);
    values.put("VALUE", value);
    values.put("TYPE", type);
    values.put("TIME", time);

    int u = db.update(questlist_table_name, values, "KEY=?", new String[]{String.valueOf(key)});
    if (u == 0) {
        db.insertWithOnConflict(questlist_table_name, null, values, SQLiteDatabase.CONFLICT_REPLACE);
    }
    qt.addQuestTrack(key);
}
 
Example 4
private synchronized void addSongsImpl(SQLiteDatabase db, int serverKey, List<Pair<String, String>> entries) {
    db.beginTransaction();
    try {
        for (Pair<String, String> entry : entries) {
            ContentValues values = new ContentValues();
            values.put(SONGS_SERVER_KEY, serverKey);
            values.put(SONGS_SERVER_ID, entry.getFirst());
            values.put(SONGS_COMPLETE_PATH, entry.getSecond());
            // Util.sleepQuietly(10000);

            db.insertWithOnConflict(TABLE_SONGS, null, values, SQLiteDatabase.CONFLICT_IGNORE);
        }

        db.setTransactionSuccessful();
    } catch (Exception ignored) {
    }

    db.endTransaction();
}
 
Example 5
Source Project: android_9.0.0_r45   File: AccountsDb.java    License: Apache License 2.0 5 votes vote down vote up
long insertOrReplaceMetaAuthTypeAndUid(String authenticatorType, int uid) {
    SQLiteDatabase db = mDeDatabase.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(META_KEY,
            META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + authenticatorType);
    values.put(META_VALUE, uid);
    return db.insertWithOnConflict(TABLE_META, null, values,
            SQLiteDatabase.CONFLICT_REPLACE);
}
 
Example 6
public void putValue(String key, String value) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put("KEY", key);
    values.put("VALUE", value);
    int u = db.update(table_name, values, "KEY=?", new String[]{key});
    if (u == 0) {
        db.insertWithOnConflict(table_name, null, values, SQLiteDatabase.CONFLICT_REPLACE);
    }
}
 
Example 7
synchronized long insertKeyValueContentValuesIntoTable(SQLiteDatabase db, String table, ContentValues contentValues) throws SQLiteException, StackOverflowError {
    return db.insertWithOnConflict(
            table,
            null,
            contentValues,
            SQLiteDatabase.CONFLICT_REPLACE
    );
}
 
Example 8
public void putResVer(String filename, long version) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put("file", filename);
    values.put("version", version);
    int u = db.update(resver_table_name, values, "file=?", new String[]{filename});
    if (u == 0) {
        db.insertWithOnConflict(resver_table_name, null, values, SQLiteDatabase.CONFLICT_REPLACE);
    }
}
 
Example 9
public void putValue(String key, String value) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put("KEY", key);
    values.put("VALUE", value);
    int u = db.update(table_name, values, "KEY=?", new String[]{key});
    if (u == 0) {
        db.insertWithOnConflict(table_name, null, values, SQLiteDatabase.CONFLICT_REPLACE);
    }
}
 
Example 10
public void putItemValue(int key, String value) {
    SQLiteDatabase db = this.getWritableDatabase();
    JsonObject obj = new JsonParser().parse(value).getAsJsonObject();
    int slotitem_id = obj.get("api_slotitem_id").getAsInt();
    ContentValues values = new ContentValues();
    values.put("KEY", key);
    values.put("KCID", slotitem_id);
    values.put("VALUE", value);
    int u = db.update(slotitem_table_name, values, "KEY=?", new String[]{String.valueOf(key)});
    if (u == 0) {
        db.insertWithOnConflict(slotitem_table_name, null, values, SQLiteDatabase.CONFLICT_REPLACE);
    }
}
 
Example 11
@Override
public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
    switch (sUriMatcher.match(uri)) {
        case VIDEO: {
            final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
            int returnCount = 0;

            db.beginTransaction();
            try {
                for (ContentValues value : values) {
                    long _id = db.insertWithOnConflict(VideoContract.VideoEntry.TABLE_NAME,
                            null, value, SQLiteDatabase.CONFLICT_REPLACE);
                    if (_id != -1) {
                        returnCount++;
                    }
                }
                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
            }

            mContentResolver.notifyChange(uri, null);
            return returnCount;
        }
        default: {
            return super.bulkInsert(uri, values);
        }
    }
}
 
Example 12
Source Project: cannonball-android   File: PoemProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Uri insert(Uri uri, ContentValues values) {
    final SQLiteDatabase db = dbHelper.getWritableDatabase();
    final long id = db.insertWithOnConflict(PoemContract.TABLE, null, values,
            SQLiteDatabase.CONFLICT_IGNORE);

    if (id > 0) {
        getContext().getContentResolver().notifyChange(uri, null);
        return ContentUris.withAppendedId(uri, id);
    } else {
        Crashlytics.log("PoemProvider: not able to insert a poem in Database");
        return null;
    }
}
 
Example 13
/**
 * Inserts NGrams into the NGram database.
 * 
 * @param db
 *            A writable {@link SQLiteDatabase}.
 * @param ngrams
 *            The set of NGrams.
 * @return The ids of the ngrams in the given set.
 */
private static Set<Long> insertNGrams(SQLiteDatabase db, Set<String> ngrams)
{
	Set<Long> nGramIds = new HashSet<Long>(ngrams.size());
	ContentValues values = new ContentValues(1);
	for (String ngram : ngrams)
	{
		values.put(NGramColumns.TEXT, ngram);
		long nGramId = db.insertWithOnConflict(FTS_NGRAM_TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
		if (nGramId == -1)
		{
			// the docs say insertWithOnConflict returns the existing row id when CONFLICT_IGNORE is specified an the values conflict with an existing
			// column, however, that doesn't seem to work reliably, so we when for an error condition and get the row id ourselves
			Cursor c = db
				.query(FTS_NGRAM_TABLE, new String[] { NGramColumns.NGRAM_ID }, NGramColumns.TEXT + "=?", new String[] { ngram }, null, null, null);
			try
			{
				if (c.moveToFirst())
				{
					nGramId = c.getLong(0);
				}
			}
			finally
			{
				c.close();
			}

		}
		nGramIds.add(nGramId);
	}
	return nGramIds;

}
 
Example 14
public void saveQuery(String searchQuery) {
    ContentValues values = new ContentValues(2);
    values.put(KEY_SUGGESTION, searchQuery);
    values.put(KEY_DATE, System.currentTimeMillis());

    SQLiteDatabase database = getWritableDatabase();
    database.insertWithOnConflict(TABLE_NAME, null, values, SQLiteDatabase.CONFLICT_REPLACE);
}
 
Example 15
private Uri insertChannelPersistent(Uri uri, ContentValues values) {
    SQLiteDatabase database;
    try {
        database = dbHelper.getWritableDatabase();
    } catch (SQLiteException e) {
        isDbWritable = false;
        SALog.printStackTrace(e);
        return uri;
    }
    if (!values.containsKey(DbParams.KEY_CHANNEL_EVENT_NAME) || !values.containsKey(DbParams.KEY_CHANNEL_RESULT)) {
        return uri;
    }
    long d = database.insertWithOnConflict(DbParams.TABLE_CHANNEL_PERSISTENT, null, values, SQLiteDatabase.CONFLICT_REPLACE);
    return ContentUris.withAppendedId(uri, d);
}
 
Example 16
Source Project: clevertap-android-sdk   File: DBAdapter.java    License: MIT License 5 votes vote down vote up
/**
 * Adds a JSON string representing to the DB.
 *
 * @param obj the JSON to record
 * @return the number of rows in the table, or DB_OUT_OF_MEMORY_ERROR/DB_UPDATE_ERROR
 */
synchronized long storeUserProfile(String id, JSONObject obj) {

    if (id == null) return DB_UPDATE_ERROR;

    if (!this.belowMemThreshold()) {
        getConfigLogger().verbose("There is not enough space left on the device to store data, data discarded");
        return DB_OUT_OF_MEMORY_ERROR;
    }

    final String tableName = Table.USER_PROFILES.getName();

    long ret = DB_UPDATE_ERROR;

    try {
        final SQLiteDatabase db = dbHelper.getWritableDatabase();
        final ContentValues cv = new ContentValues();
        cv.put(KEY_DATA, obj.toString());
        cv.put("_id", id);
        ret = db.insertWithOnConflict(tableName, null, cv, SQLiteDatabase.CONFLICT_REPLACE);
    } catch (final SQLiteException e) {
        getConfigLogger().verbose("Error adding data to table " + tableName + " Recreating DB");
        dbHelper.deleteDatabase();
    } finally {
        dbHelper.close();
    }
    return ret;
}
 
Example 17
@Override
public void clear() throws RemoteException {
	try {
		enforcePermission(0);
		SQLiteDatabase db = getDb();
		SQLiteDatabase dbUsage = getDbUsage();
		if (db == null || dbUsage == null)
			return;

		mLock.writeLock().lock();
		try {
			db.beginTransaction();
			try {
				db.execSQL("DELETE FROM " + cTableRestriction);
				db.execSQL("DELETE FROM " + cTableSetting);
				Util.log(null, Log.WARN, "Database cleared");

				// Reset migrated
				ContentValues values = new ContentValues();
				values.put("uid", 0);
				values.put("type", "");
				values.put("name", PrivacyManager.cSettingMigrated);
				values.put("value", Boolean.toString(true));
				db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE);

				db.setTransactionSuccessful();
			} finally {
				db.endTransaction();
			}
		} finally {
			mLock.writeLock().unlock();
		}

		// Clear caches
		synchronized (mRestrictionCache) {
			mRestrictionCache.clear();
		}
		synchronized (mSettingCache) {
			mSettingCache.clear();
		}
		synchronized (mAskedOnceCache) {
			mAskedOnceCache.clear();
		}
		Util.log(null, Log.WARN, "Caches cleared");

		mLockUsage.writeLock().lock();
		try {
			dbUsage.beginTransaction();
			try {
				dbUsage.execSQL("DELETE FROM " + cTableUsage);
				Util.log(null, Log.WARN, "Usage database cleared");

				dbUsage.setTransactionSuccessful();
			} finally {
				dbUsage.endTransaction();
			}
		} finally {
			mLockUsage.writeLock().unlock();
		}

	} catch (Throwable ex) {
		Util.bug(null, ex);
		throw new RemoteException(ex.toString());
	}
}
 
Example 18
@Override
public long insert(SQLiteDatabase db, Uri uri, ContentValues contentValues) {
    return db.insertWithOnConflict(tableName, "", contentValues, SQLiteDatabase.CONFLICT_REPLACE);
}
 
Example 19
@Override
public Uri insert(@NonNull Uri uri, ContentValues values)
{
  Log.info("[GameProvider] Inserting row at URI: " + uri);

  SQLiteDatabase database = mDbHelper.getWritableDatabase();
  String table = uri.getLastPathSegment();

  long id = -1;

  if (table != null)
  {
    if (table.equals(REFRESH_LIBRARY))
    {
      Log.info(
              "[GameProvider] URI specified table REFRESH_LIBRARY. No insertion necessary; refreshing library contents...");
      mDbHelper.scanLibrary(database);
      return uri;
    }

    id = database.insertWithOnConflict(table, null, values, SQLiteDatabase.CONFLICT_IGNORE);

    // If insertion was successful...
    if (id > 0)
    {
      // If we just added a folder, add its contents to the game list.
      if (table.equals(GameDatabase.TABLE_NAME_FOLDERS))
      {
        mDbHelper.scanLibrary(database);
      }

      // Notify the UI that its contents should be refreshed.
      getContext().getContentResolver().notifyChange(uri, null);
      uri = Uri.withAppendedPath(uri, Long.toString(id));
    }
    else
    {
      Log.error("[GameProvider] Row already exists: " + uri + " id: " + id);
    }
  }
  else
  {
    Log.error("[GameProvider] Badly formatted URI: " + uri);
  }

  database.close();

  return uri;
}
 
Example 20
private void setSettingInternal(PSetting setting) throws RemoteException {
	try {
		SQLiteDatabase db = getDb();
		if (db == null)
			return;

		mLock.writeLock().lock();
		try {
			db.beginTransaction();
			try {
				if (setting.value == null)
					db.delete(cTableSetting, "uid=? AND type=? AND name=?",
							new String[] { Integer.toString(setting.uid), setting.type, setting.name });
				else {
					// Create record
					ContentValues values = new ContentValues();
					values.put("uid", setting.uid);
					values.put("type", setting.type);
					values.put("name", setting.name);
					values.put("value", setting.value);

					// Insert/update record
					db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE);
				}

				db.setTransactionSuccessful();
			} finally {
				db.endTransaction();
			}
		} finally {
			mLock.writeLock().unlock();
		}

		if (PrivacyManager.cSettingAOSPMode.equals(setting.name))
			if (setting.value == null || Boolean.toString(false).equals(setting.value))
				new File("/data/system/xprivacy/aosp").delete();
			else
				new File("/data/system/xprivacy/aosp").createNewFile();

		// Update cache
		CSetting key = new CSetting(setting.uid, setting.type, setting.name);
		key.setValue(setting.value);
		synchronized (mSettingCache) {
			if (mSettingCache.containsKey(key))
				mSettingCache.remove(key);
			if (setting.value != null)
				mSettingCache.put(key, key);
		}

		// Clear restrictions for white list
		if (Meta.isWhitelist(setting.type))
			for (String restrictionName : PrivacyManager.getRestrictions())
				for (Hook hook : PrivacyManager.getHooks(restrictionName, null))
					if (setting.type.equals(hook.whitelist())) {
						PRestriction restriction = new PRestriction(setting.uid, hook.getRestrictionName(),
								hook.getName());
						Util.log(null, Log.WARN, "Clearing cache for " + restriction);
						synchronized (mRestrictionCache) {
							for (CRestriction mkey : new ArrayList<CRestriction>(mRestrictionCache.keySet()))
								if (mkey.isSameMethod(restriction)) {
									Util.log(null, Log.WARN, "Removing " + mkey);
									mRestrictionCache.remove(mkey);
								}
						}
					}
	} catch (Throwable ex) {
		Util.bug(null, ex);
		throw new RemoteException(ex.toString());
	}
}