Example usage for android.database.sqlite SQLiteDatabase CONFLICT_IGNORE

List of usage examples for android.database.sqlite SQLiteDatabase CONFLICT_IGNORE

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteDatabase CONFLICT_IGNORE.

Prototype

int CONFLICT_IGNORE

To view the source code for android.database.sqlite SQLiteDatabase CONFLICT_IGNORE.

Click Source Link

Document

When a constraint violation occurs, the one row that contains the constraint violation is not inserted or changed.

Usage

From source file:company.test.Test.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    switch (id) {
    case R.id.add_item:
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Add a task");
        builder.setMessage("What do you want to do?");
        final EditText inputField = new EditText(this);
        builder.setView(inputField);/*from  www.jav a  2s.c om*/
        builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String task = inputField.getText().toString();
                Log.d("MainActivity", task);

                SQLiteDatabase db = helper.getWritableDatabase();
                ContentValues values = new ContentValues();

                values.clear();
                values.put(ItemContract.Columns.ITEM, task);

                db.insertWithOnConflict(ItemContract.TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);

                activity.updateUI();
            }
        });

        builder.setNegativeButton("Cancel", null);

        builder.create().show();
        return true;
    case R.id.action_settings:
        Log.d("MainActivity", "Settings");
        return true;
    default:
        return false;
    }
}

From source file:com.shalzz.attendance.DatabaseHandler.java

/**
 * Add new Subject//  ww w  . j a  va 2  s.co m
 * @param subject the {@link Subject} to add
 */
public void addSubject(Subject subject, long timestamp) {
    SQLiteDatabase db = getWritableDatabase();

    db.insertWithOnConflict(Subject.TABLE_NAME, null,
            Subject.FACTORY.marshal().id(subject.id()).name(subject.name()).attended(subject.attended())
                    .held(subject.held()).last_updated(timestamp).asContentValues(),
            SQLiteDatabase.CONFLICT_REPLACE);

    // Store the dates in another table corresponding to the same id
    for (Date date : subject.absent_dates()) {
        db.insertWithOnConflict(AbsentDate.TABLE_NAME, null,
                AbsentDate.FACTORY.marshal().subject_id(subject.id()).absent_date(date).asContentValues(),
                SQLiteDatabase.CONFLICT_IGNORE);
    }
}

From source file:github.popeen.dsub.util.SongDBHandler.java

protected synchronized void addSongImpl(SQLiteDatabase db, int serverKey, String id, String absolutePath) {
    ContentValues values = new ContentValues();
    values.put(SONGS_SERVER_KEY, serverKey);
    values.put(SONGS_SERVER_ID, id);//  w  w w.  ja v  a 2 s. c  o  m
    values.put(SONGS_COMPLETE_PATH, absolutePath);

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

From source file:com.sina.weibo.sdk.demo.sample.activity.TestFragment.java

public void saveData(ArrayList<Status> statusList) {
    SQLiteDatabase databaseHelper = Utils.getDatabaseHelper().getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    for (Status status : statusList) {
        //            contentValues.put("id", Long.parseLong(status.idstr));
        contentValues.put("name", status.user.name);
        contentValues.put("gender", status.user.gender);
        contentValues.put("location", status.user.location);
        contentValues.put("description", status.user.description);
        contentValues.put("followers_count", status.user.followers_count);
        contentValues.put("friends_count", status.user.friends_count);
        contentValues.put("statuses_count", status.user.statuses_count);
        contentValues.put("main_content", status.text);
        contentValues.put("created_at", status.created_at);
        contentValues.put("source", status.source);
        if (status.retweeted_status != null) {
            contentValues.put("sub_status", status.retweeted_status != null ? 1 : 0);
            contentValues.put("sub_name", status.retweeted_status.user.name);
            contentValues.put("sub_content", status.retweeted_status.text);
        }//from w  ww .j  ava 2s  .  c  o  m
    }
    databaseHelper.insertWithOnConflict("Status", null, contentValues, SQLiteDatabase.CONFLICT_IGNORE);
    databaseHelper.close();

}

From source file:github.popeen.dsub.util.SongDBHandler.java

protected synchronized void addSongsImpl(SQLiteDatabase db, int serverKey, List<Pair<String, String>> entries) {
    db.beginTransaction();/*from ww  w . ja  v  a 2 s. c  om*/
    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());

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

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

    db.endTransaction();
}

From source file:de.vanita5.twittnuker.provider.TwidereDataProvider.java

@Override
public int bulkInsert(final Uri uri, @NonNull final ContentValues[] valuesArray) {
    try {//from w ww .j a v a  2  s  .  c om
        final int tableId = getTableId(uri);
        final String table = getTableNameById(tableId);
        switch (tableId) {
        case TABLE_ID_DIRECT_MESSAGES_CONVERSATION:
        case TABLE_ID_DIRECT_MESSAGES:
        case TABLE_ID_DIRECT_MESSAGES_CONVERSATIONS_ENTRIES:
            return 0;
        }
        int result = 0;
        final long[] newIds = new long[valuesArray.length];
        if (table != null) {
            mDatabaseWrapper.beginTransaction();
            if (tableId == TABLE_ID_CACHED_USERS) {
                for (final ContentValues values : valuesArray) {
                    final Expression where = Expression.equals(CachedUsers.USER_ID,
                            values.getAsLong(CachedUsers.USER_ID));
                    mDatabaseWrapper.update(table, values, where.getSQL(), null);
                    newIds[result++] = mDatabaseWrapper.insertWithOnConflict(table, null, values,
                            SQLiteDatabase.CONFLICT_IGNORE);
                }
            } else if (tableId == TABLE_ID_SEARCH_HISTORY) {
                for (final ContentValues values : valuesArray) {
                    values.put(SearchHistory.RECENT_QUERY, System.currentTimeMillis());
                    final Expression where = Expression.equalsArgs(SearchHistory.QUERY);
                    final String[] args = { values.getAsString(SearchHistory.QUERY) };
                    mDatabaseWrapper.update(table, values, where.getSQL(), args);
                    newIds[result++] = mDatabaseWrapper.insertWithOnConflict(table, null, values,
                            SQLiteDatabase.CONFLICT_IGNORE);
                }
            } else if (shouldReplaceOnConflict(tableId)) {
                for (final ContentValues values : valuesArray) {
                    newIds[result++] = mDatabaseWrapper.insertWithOnConflict(table, null, values,
                            SQLiteDatabase.CONFLICT_REPLACE);
                }
            } else {
                for (final ContentValues values : valuesArray) {
                    newIds[result++] = mDatabaseWrapper.insert(table, null, values);
                }
            }
            mDatabaseWrapper.setTransactionSuccessful();
            mDatabaseWrapper.endTransaction();
        }
        if (result > 0) {
            onDatabaseUpdated(tableId, uri);
        }
        onNewItemsInserted(uri, tableId, valuesArray, newIds);
        return result;
    } catch (final SQLException e) {
        throw new IllegalStateException(e);
    }
}

From source file:cn.edu.wyu.documentviewer.RecentsProvider.java

@Override
public Uri insert(Uri uri, ContentValues values) {
    final SQLiteDatabase db = mHelper.getWritableDatabase();
    final ContentValues key = new ContentValues();
    switch (sMatcher.match(uri)) {
    case URI_RECENT:
        values.put(RecentColumns.TIMESTAMP, System.currentTimeMillis());
        db.insert(TABLE_RECENT, null, values);
        final long cutoff = System.currentTimeMillis() - MAX_HISTORY_IN_MILLIS;
        db.delete(TABLE_RECENT, RecentColumns.TIMESTAMP + "<" + cutoff, null);
        return uri;
    case URI_STATE:
        final String authority = uri.getPathSegments().get(1);
        final String rootId = uri.getPathSegments().get(2);
        final String documentId = uri.getPathSegments().get(3);

        key.put(StateColumns.AUTHORITY, authority);
        key.put(StateColumns.ROOT_ID, rootId);
        key.put(StateColumns.DOCUMENT_ID, documentId);

        // Ensure that row exists, then update with changed values
        db.insertWithOnConflict(TABLE_STATE, null, key, SQLiteDatabase.CONFLICT_IGNORE);
        db.update(TABLE_STATE, values, StateColumns.AUTHORITY + "=? AND " + StateColumns.ROOT_ID + "=? AND "
                + StateColumns.DOCUMENT_ID + "=?", new String[] { authority, rootId, documentId });

        return uri;
    case URI_RESUME:
        values.put(ResumeColumns.TIMESTAMP, System.currentTimeMillis());

        final String packageName = uri.getPathSegments().get(1);
        key.put(ResumeColumns.PACKAGE_NAME, packageName);

        // Ensure that row exists, then update with changed values
        db.insertWithOnConflict(TABLE_RESUME, null, key, SQLiteDatabase.CONFLICT_IGNORE);
        db.update(TABLE_RESUME, values, ResumeColumns.PACKAGE_NAME + "=?", new String[] { packageName });
        return uri;
    default:/*from   w  w  w .  jav  a 2  s  .  c o m*/
        throw new UnsupportedOperationException("Unsupported Uri " + uri);
    }
}

From source file:org.getlantern.firetweet.provider.FiretweetDataProvider.java

@Override
public int bulkInsert(final Uri uri, @NonNull final ContentValues[] valuesArray) {
    try {/*from www  . jav  a  2  s.c  o m*/
        final int tableId = getTableId(uri);
        final String table = getTableNameById(tableId);
        checkWritePermission(tableId, table);
        switch (tableId) {
        case TABLE_ID_DIRECT_MESSAGES_CONVERSATION:
        case TABLE_ID_DIRECT_MESSAGES:
        case TABLE_ID_DIRECT_MESSAGES_CONVERSATIONS_ENTRIES:
            return 0;
        }
        int result = 0;
        final long[] newIds = new long[valuesArray.length];
        if (table != null) {
            mDatabaseWrapper.beginTransaction();
            if (tableId == TABLE_ID_CACHED_USERS) {
                for (final ContentValues values : valuesArray) {
                    final Expression where = Expression.equals(CachedUsers.USER_ID,
                            values.getAsLong(CachedUsers.USER_ID));
                    mDatabaseWrapper.update(table, values, where.getSQL(), null);
                    newIds[result++] = mDatabaseWrapper.insertWithOnConflict(table, null, values,
                            SQLiteDatabase.CONFLICT_REPLACE);
                }
            } else if (tableId == TABLE_ID_SEARCH_HISTORY) {
                for (final ContentValues values : valuesArray) {
                    values.put(SearchHistory.RECENT_QUERY, System.currentTimeMillis());
                    final Expression where = Expression.equalsArgs(SearchHistory.QUERY);
                    final String[] args = { values.getAsString(SearchHistory.QUERY) };
                    mDatabaseWrapper.update(table, values, where.getSQL(), args);
                    newIds[result++] = mDatabaseWrapper.insertWithOnConflict(table, null, values,
                            SQLiteDatabase.CONFLICT_IGNORE);
                }
            } else if (shouldReplaceOnConflict(tableId)) {
                for (final ContentValues values : valuesArray) {
                    newIds[result++] = mDatabaseWrapper.insertWithOnConflict(table, null, values,
                            SQLiteDatabase.CONFLICT_REPLACE);
                }
            } else {
                for (final ContentValues values : valuesArray) {
                    newIds[result++] = mDatabaseWrapper.insert(table, null, values);
                }
            }
            mDatabaseWrapper.setTransactionSuccessful();
            mDatabaseWrapper.endTransaction();
        }
        if (result > 0) {
            onDatabaseUpdated(tableId, uri);
        }
        onNewItemsInserted(uri, tableId, valuesArray, newIds);
        return result;
    } catch (final SQLException e) {
        Crashlytics.logException(e);
        throw new IllegalStateException(e);
    }
}

From source file:com.cyanogenmod.eleven.provider.LocalizedStore.java

private void updateArtistData(SQLiteDatabase db, long id, String name) {
    mContentValues.clear();/*from   w  ww .  j av  a  2 s .c  o  m*/
    name = MusicUtils.getTrimmedName(name);

    final LocaleUtils localeUtils = LocaleUtils.getInstance();
    final int bucketIndex = localeUtils.getBucketIndex(name);

    mContentValues.put(ArtistSortColumns.ID, id);
    mContentValues.put(ArtistSortColumns.NAME, name);
    mContentValues.put(ArtistSortColumns.NAME_BUCKET, bucketIndex);
    mContentValues.put(ArtistSortColumns.NAME_LABEL, localeUtils.getBucketLabel(bucketIndex));

    db.insertWithOnConflict(ArtistSortColumns.TABLE_NAME, null, mContentValues, SQLiteDatabase.CONFLICT_IGNORE);
}

From source file:com.cyanogenmod.eleven.provider.LocalizedStore.java

private void updateAlbumData(SQLiteDatabase db, long id, String name, long artistId) {
    mContentValues.clear();/* w w  w  . j a  v  a  2  s  . c  o  m*/
    name = MusicUtils.getTrimmedName(name);

    final LocaleUtils localeUtils = LocaleUtils.getInstance();
    final int bucketIndex = localeUtils.getBucketIndex(name);

    mContentValues.put(AlbumSortColumns.ID, id);
    mContentValues.put(AlbumSortColumns.NAME, name);
    mContentValues.put(AlbumSortColumns.NAME_BUCKET, bucketIndex);
    mContentValues.put(AlbumSortColumns.NAME_LABEL, localeUtils.getBucketLabel(bucketIndex));
    mContentValues.put(AlbumSortColumns.ARTIST_ID, artistId);

    db.insertWithOnConflict(AlbumSortColumns.TABLE_NAME, null, mContentValues, SQLiteDatabase.CONFLICT_IGNORE);
}