Example usage for android.database.sqlite SQLiteDatabase CONFLICT_REPLACE

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

Introduction

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

Prototype

int CONFLICT_REPLACE

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

Click Source Link

Document

When a UNIQUE constraint violation occurs, the pre-existing rows that are causing the constraint violation are removed prior to inserting or updating the current row.

Usage

From source file:co.rewen.statex.AsyncLocalStorageUtil.java

/**
 * Sets the value for the key given, returns true if successful, false otherwise.
 *//*from  ww w.j  av  a 2  s  . c  o m*/
/* package */
static boolean setItemImpl(SQLiteDatabase db, String key, String value) {
    ContentValues contentValues = new ContentValues();
    contentValues.put(KEY_COLUMN, key);
    contentValues.put(VALUE_COLUMN, value);

    long inserted = db.insertWithOnConflict(TABLE_STATE, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE);

    return (-1 != inserted);
}

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

/**
 * Add new Subject// w ww .  j a va2 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:com.andreadec.musicplayer.IndexFolderService.java

private void index(File folder) {
    File files[] = folder.listFiles(new AudioFileFilter());
    File subfolders[] = folder.listFiles(new DirectoryFilter());

    for (File subfolder : subfolders) {
        if (subfolder != null && subfolder.canRead()) {
            index(subfolder);/*from  w  w w .  j av a2  s .  c o  m*/
        }
    }

    for (File file : files) {
        String uri = file.getAbsolutePath();
        BrowserSong song = new BrowserSong(file.getAbsolutePath(), null);
        ContentValues values = new ContentValues();
        values.put("uri", uri);
        values.put("artist", song.getArtist());
        values.put("title", song.getTitle());
        Integer trackNumber = song.getTrackNumber();
        if (trackNumber == null)
            trackNumber = -1;
        values.put("trackNumber", trackNumber);
        values.put("hasImage", song.hasImage());
        db.insertWithOnConflict("Songs", null, values, SQLiteDatabase.CONFLICT_REPLACE);
    }
}

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

public void importData(JSONArray array) {
    SQLiteDatabase db = this.getReadableDatabase();
    try {/*  www.  jav  a2 s  .c om*/
        for (int i = 0; i < array.length(); i++) {
            JSONObject row = array.getJSONObject(i);
            ContentValues values = new ContentValues();
            values.put(SONGS_ID, row.getInt("SONGS_ID"));
            values.put(SONGS_SERVER_KEY, row.getInt("SONGS_SERVER_KEY"));
            values.put(SONGS_SERVER_ID, row.getString("SONGS_SERVER_ID"));
            values.put(SONGS_COMPLETE_PATH, row.getString("SONGS_COMPLETE_PATH"));
            values.put(SONGS_LAST_PLAYED, row.getInt("SONGS_LAST_PLAYED"));
            values.put(SONGS_LAST_COMPLETED, row.getInt("SONGS_LAST_COMPLETED"));
            db.insertWithOnConflict(TABLE_SONGS, null, values, SQLiteDatabase.CONFLICT_REPLACE);
        }
    } catch (Exception e) {
    }
}

From source file:org.tomahawk.libtomahawk.database.DatabaseHelper.java

/**
 * Store the given {@link Playlist}//from ww w.ja  va  2  s.co  m
 *
 * @param playlist       the given {@link Playlist}
 * @param reverseEntries set to true, if the order of the entries should be reversed before
 *                       storing in the database
 */
public void storePlaylist(final Playlist playlist, final boolean reverseEntries) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            synchronized (this) {
                ContentValues values = new ContentValues();
                values.put(TomahawkSQLiteHelper.PLAYLISTS_COLUMN_NAME, playlist.getName());
                values.put(TomahawkSQLiteHelper.PLAYLISTS_COLUMN_CURRENTREVISION,
                        playlist.getCurrentRevision());
                values.put(TomahawkSQLiteHelper.PLAYLISTS_COLUMN_ID, playlist.getId());
                values.put(TomahawkSQLiteHelper.PLAYLISTS_COLUMN_HATCHETID, playlist.getHatchetId());

                mDatabase.beginTransaction();
                mDatabase.insertWithOnConflict(TomahawkSQLiteHelper.TABLE_PLAYLISTS, null, values,
                        SQLiteDatabase.CONFLICT_REPLACE);
                // Delete every already associated Track entry
                mDatabase.delete(TomahawkSQLiteHelper.TABLE_TRACKS,
                        TomahawkSQLiteHelper.TRACKS_COLUMN_PLAYLISTID + " = ?",
                        new String[] { playlist.getId() });

                // Store every single Track in the database and store the relationship
                // by storing the playlists's id with it
                ArrayList<PlaylistEntry> entries = playlist.getEntries();
                for (int i = 0; i < entries.size(); i++) {
                    PlaylistEntry entry;
                    if (reverseEntries) {
                        entry = entries.get(entries.size() - 1 - i);
                    } else {
                        entry = entries.get(i);
                    }
                    values.clear();
                    values.put(TomahawkSQLiteHelper.TRACKS_COLUMN_PLAYLISTID, playlist.getId());
                    values.put(TomahawkSQLiteHelper.TRACKS_COLUMN_TRACKNAME,
                            entry.getQuery().getBasicTrack().getName());
                    values.put(TomahawkSQLiteHelper.TRACKS_COLUMN_ARTISTNAME,
                            entry.getQuery().getBasicTrack().getArtist().getName());
                    values.put(TomahawkSQLiteHelper.TRACKS_COLUMN_ALBUMNAME,
                            entry.getQuery().getBasicTrack().getAlbum().getName());
                    values.put(TomahawkSQLiteHelper.TRACKS_COLUMN_RESULTHINT,
                            entry.getQuery().getTopTrackResultKey());
                    values.put(TomahawkSQLiteHelper.TRACKS_COLUMN_PLAYLISTENTRYINDEX, i);
                    if (entry.getQuery().isFetchedViaHatchet()) {
                        values.put(TomahawkSQLiteHelper.TRACKS_COLUMN_ISFETCHEDVIAHATCHET, TRUE);
                    } else {
                        values.put(TomahawkSQLiteHelper.TRACKS_COLUMN_ISFETCHEDVIAHATCHET, FALSE);
                    }
                    values.put(TomahawkSQLiteHelper.TRACKS_COLUMN_PLAYLISTENTRYID, entry.getId());
                    mDatabase.insert(TomahawkSQLiteHelper.TABLE_TRACKS, null, values);
                }
                mDatabase.setTransactionSuccessful();
                mDatabase.endTransaction();
                sendReportResultsBroadcast(playlist.getId());
            }
        }
    }).start();
}

From source file:zlyh.dmitry.recaller.services.SqlService.java

private synchronized void save(RecordModel model) {
    // -1 means no id yet, new record
    if (model.getId() == -1) {
        ContentValues values = new ContentValues();
        values.put(SQLHelper.C_FILENAME, model.getFile_name());
        values.put(SQLHelper.C_PATH, model.getPath());
        values.put(SQLHelper.C_DURATION, model.getDuration());
        values.put(SQLHelper.C_DATE, model.getReadable_time());
        values.put(SQLHelper.C_START, model.getTime_start());
        values.put(SQLHelper.C_END, model.getTime_end());
        values.put(SQLHelper.C_FAVORITE, model.isFavorite());
        values.put(SQLHelper.C_CUSTOM_NAME, model.getCustom_name());
        values.put(SQLHelper.C_PHONE, model.getPhone());
        values.put(SQLHelper.C_INCOMING, model.isIncoming());

        long id = SQLHelper.getInstance().getWritableDatabase().insert(SQLHelper.TABLE_NAME, null, values);
        if (id != -1) {
            model.setId((int) id);
        }/*from w  w  w . j a va2 s. c om*/

        Intent model_broadcast = new Intent(Const.SqlService.BROADCAST)
                .putExtra(Const.COMMAND, Const.SqlService.SAVE).putExtra(Const.MODEL, model);
        LocalBroadcastManager.getInstance(this).sendBroadcast(model_broadcast);
    } else {
        //existing record
        ContentValues values = new ContentValues();
        values.put(SQLHelper.C_FAVORITE, model.isFavorite());
        values.put(SQLHelper.C_CUSTOM_NAME, model.getCustom_name());

        SQLHelper.getInstance().getWritableDatabase().updateWithOnConflict(SQLHelper.TABLE_NAME, values,
                SQLHelper.C_ID + " = ?", new String[] { String.valueOf(model.getId()) },
                SQLiteDatabase.CONFLICT_REPLACE);

    }

}

From source file:syncthing.android.service.ServiceSettingsProvider.java

private long putTextSetting(String key, String val) {
    ReentrantReadWriteLock.WriteLock lock = mLock.writeLock();
    try {// w  ww . j a v  a  2 s .  c  o  m
        lock.lock();
        ContentValues cv = new ContentValues(2);
        cv.put(ServiceSettingsDB.SCHEMA.KEY, key);
        cv.put(ServiceSettingsDB.SCHEMA.TEXT_VAL, val);
        return mDB.getWritableDatabase().insertWithOnConflict(ServiceSettingsDB.SCHEMA.TABLE, null, cv,
                SQLiteDatabase.CONFLICT_REPLACE);
    } finally {
        lock.unlock();
    }
}

From source file:ru.gkpromtech.exhibition.events.EventDetailsActivity.java

@Override
public void onFavoriteClicked(int eventId, int state) {
    EventReader.getInstance(context).updateFavorite(eventId, state, SQLiteDatabase.CONFLICT_REPLACE);

    if (!changedItems.contains(eventId)) {
        changedItems.add(eventId);//from   w ww. j  ava  2 s. co m
    }

    final int eventid = eventId;
    Event e = EventReader.getInstance(context).findItem(eventId);
    if (e != null) {

        EventCalendar cal = EventCalendar.getInstance(context);
        cal.setEventCalendarInteractionListener(new EventCalendar.EventCalendarInteraction() {
            @Override
            public void eventInserted(int calEventId) {
                EventReader.getInstance(context).updateCalendarEvent(eventid, calEventId,
                        SQLiteDatabase.CONFLICT_REPLACE);
            }

            @Override
            public void eventRemoved(int calEventId) {
                EventReader.getInstance(context).updateCalendarEvent(eventid, -1,
                        SQLiteDatabase.CONFLICT_REPLACE);
            }
        });

        // add to calendar
        if (state == 1) {
            // get places for event
            List<Place> places = EventReader.getInstance(context).getPlaces(eventId);
            String[] sPlaces = new String[places.size()];
            for (int i = 0; i < places.size(); i++) {
                sPlaces[i] = places.get(i).name;
            }

            EventCalendar.getInstance(context).insertEventToCalendar(e.header, e.details,
                    TextUtils.join(", ", sPlaces), e.date, true);
        }
        // remove from calendar
        else {
            EventFavorite fav = EventReader.getInstance(context).getEventFavorite(eventId);
            if (fav.calendarEventId != null) {
                EventCalendar.getInstance(context).removeEventFromCalendar(fav.calendarEventId);
            }
        }
    }
}

From source file:syncthing.android.service.ServiceSettingsProvider.java

private long putIntSetting(String key, int val) {
    ReentrantReadWriteLock.WriteLock lock = mLock.writeLock();
    try {/*from  w w  w. j  av a  2s. co  m*/
        lock.lock();
        ContentValues cv = new ContentValues(2);
        cv.put(ServiceSettingsDB.SCHEMA.KEY, key);
        cv.put(ServiceSettingsDB.SCHEMA.INT_VAL, val);
        return mDB.getWritableDatabase().insertWithOnConflict(ServiceSettingsDB.SCHEMA.TABLE, null, cv,
                SQLiteDatabase.CONFLICT_REPLACE);
    } finally {
        lock.unlock();
    }
}

From source file:ru.gkpromtech.exhibition.events.EventsActivity.java

@Override
public void onFavoriteChanged(int pageNumber, final int eventId, int state) {
    EventReader.getInstance(this).updateFavorite(eventId, state, SQLiteDatabase.CONFLICT_REPLACE);

    final int eventid = eventId;
    final Context context = this;
    Event e = EventReader.getInstance(this).findItem(eventId);
    if (e != null) {

        EventCalendar cal = EventCalendar.getInstance(this);
        cal.setEventCalendarInteractionListener(new EventCalendar.EventCalendarInteraction() {
            @Override//ww w  .j  a  va 2 s.c o  m
            public void eventInserted(int calEventId) {
                EventReader.getInstance(context).updateCalendarEvent(eventid, calEventId,
                        SQLiteDatabase.CONFLICT_REPLACE);
                AnalyticsManager.sendEvent(EventsActivity.this, R.string.events_category,
                        R.string.action_favorite_add, eventId);
            }

            @Override
            public void eventRemoved(int calEventId) {
                EventReader.getInstance(context).updateCalendarEvent(eventid, -1,
                        SQLiteDatabase.CONFLICT_REPLACE);
                AnalyticsManager.sendEvent(EventsActivity.this, R.string.events_category,
                        R.string.action_favorite_removed, eventId);
            }
        });

        // add to calendar
        if (state == 1) {
            // get places for event
            List<Place> places = EventReader.getInstance(this).getPlaces(eventId);
            String[] sPlaces = new String[places.size()];
            for (int i = 0; i < places.size(); i++) {
                sPlaces[i] = places.get(i).name;
            }

            EventCalendar.getInstance(this).insertEventToCalendar(e.header, e.details,
                    TextUtils.join(", ", sPlaces), e.date, true);
        }
        // remove from calendar
        else {
            EventFavorite fav = EventReader.getInstance(this).getEventFavorite(eventId);
            if (fav.calendarEventId != null) {
                EventCalendar.getInstance(this).removeEventFromCalendar(fav.calendarEventId);
            }
        }
    }
}