Example usage for android.database.sqlite SQLiteDatabase delete

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

Introduction

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

Prototype

public int delete(String table, String whereClause, String[] whereArgs) 

Source Link

Document

Convenience method for deleting rows in the database.

Usage

From source file:org.frc836.database.DBSyncService.java

private void processWheelBase(JSONArray wheelBase) {
    try {//  w ww .j a  v  a 2s .  c  o m
        for (int i = 0; i < wheelBase.length(); i++) {
            JSONObject row = wheelBase.getJSONObject(i);
            Action action = Action.UPDATE;
            if (row.getInt(WHEEL_BASE_LU_Entry.COLUMN_NAME_INVALID) != 0) {
                action = Action.DELETE;
            }
            ContentValues vals = new ContentValues();
            vals.put(WHEEL_BASE_LU_Entry.COLUMN_NAME_ID, row.getInt(WHEEL_BASE_LU_Entry.COLUMN_NAME_ID));
            vals.put(WHEEL_BASE_LU_Entry.COLUMN_NAME_WHEEL_BASE_DESC,
                    row.getString(WHEEL_BASE_LU_Entry.COLUMN_NAME_WHEEL_BASE_DESC));
            vals.put(WHEEL_BASE_LU_Entry.COLUMN_NAME_TIMESTAMP, DB.dateParser
                    .format(new Date(row.getLong(WHEEL_BASE_LU_Entry.COLUMN_NAME_TIMESTAMP) * 1000)));

            // check if this entry exists already
            String[] projection = { WHEEL_BASE_LU_Entry.COLUMN_NAME_WHEEL_BASE_DESC };
            String[] where = { vals.getAsString(WHEEL_BASE_LU_Entry.COLUMN_NAME_ID) };

            synchronized (ScoutingDBHelper.lock) {

                SQLiteDatabase db = ScoutingDBHelper.getInstance().getWritableDatabase();

                Cursor c = db.query(WHEEL_BASE_LU_Entry.TABLE_NAME, projection, // select
                        WHEEL_BASE_LU_Entry.COLUMN_NAME_ID + "=?", where, null, // don't
                        // group
                        null, // don't filter
                        null, // don't order
                        "0,1"); // limit to 1
                try {
                    if (!c.moveToFirst()) {
                        if (action == Action.UPDATE)
                            action = Action.INSERT;
                        else if (action == Action.DELETE)
                            action = Action.NOTHING;
                    }

                    switch (action) {
                    case UPDATE:
                        db.update(WHEEL_BASE_LU_Entry.TABLE_NAME, vals,
                                WHEEL_BASE_LU_Entry.COLUMN_NAME_ID + " = ?", where);
                        break;
                    case INSERT:
                        db.insert(WHEEL_BASE_LU_Entry.TABLE_NAME, null, vals);
                        break;
                    case DELETE:
                        db.delete(WHEEL_BASE_LU_Entry.TABLE_NAME, WHEEL_BASE_LU_Entry.COLUMN_NAME_ID + " = ?",
                                where);
                        break;
                    default:
                    }
                } finally {
                    if (c != null)
                        c.close();
                    ScoutingDBHelper.getInstance().close();
                }
            }
        }
    } catch (JSONException e) {
        // TODO handle error
    }
}

From source file:org.frc836.database.DBSyncService.java

private void processWheelType(JSONArray wheelType) {
    try {//  w  ww  . j ava  2  s  .co  m
        for (int i = 0; i < wheelType.length(); i++) {
            JSONObject row = wheelType.getJSONObject(i);
            Action action = Action.UPDATE;
            if (row.getInt(WHEEL_TYPE_LU_Entry.COLUMN_NAME_INVALID) != 0) {
                action = Action.DELETE;
            }
            ContentValues vals = new ContentValues();
            vals.put(WHEEL_TYPE_LU_Entry.COLUMN_NAME_ID, row.getInt(WHEEL_TYPE_LU_Entry.COLUMN_NAME_ID));
            vals.put(WHEEL_TYPE_LU_Entry.COLUMN_NAME_WHEEL_TYPE_DESC,
                    row.getString(WHEEL_TYPE_LU_Entry.COLUMN_NAME_WHEEL_TYPE_DESC));
            vals.put(WHEEL_TYPE_LU_Entry.COLUMN_NAME_TIMESTAMP, DB.dateParser
                    .format(new Date(row.getLong(WHEEL_TYPE_LU_Entry.COLUMN_NAME_TIMESTAMP) * 1000)));

            // check if this entry exists already
            String[] projection = { WHEEL_TYPE_LU_Entry.COLUMN_NAME_WHEEL_TYPE_DESC };
            String[] where = { vals.getAsString(WHEEL_TYPE_LU_Entry.COLUMN_NAME_ID) };

            synchronized (ScoutingDBHelper.lock) {

                SQLiteDatabase db = ScoutingDBHelper.getInstance().getWritableDatabase();

                Cursor c = db.query(WHEEL_TYPE_LU_Entry.TABLE_NAME, projection, // select
                        WHEEL_TYPE_LU_Entry.COLUMN_NAME_ID + "=?", where, null, // don't
                        // group
                        null, // don't filter
                        null, // don't order
                        "0,1"); // limit to 1
                try {
                    if (!c.moveToFirst()) {
                        if (action == Action.UPDATE)
                            action = Action.INSERT;
                        else if (action == Action.DELETE)
                            action = Action.NOTHING;
                    }

                    switch (action) {
                    case UPDATE:
                        db.update(WHEEL_TYPE_LU_Entry.TABLE_NAME, vals,
                                WHEEL_TYPE_LU_Entry.COLUMN_NAME_ID + " = ?", where);
                        break;
                    case INSERT:
                        db.insert(WHEEL_TYPE_LU_Entry.TABLE_NAME, null, vals);
                        break;
                    case DELETE:
                        db.delete(WHEEL_TYPE_LU_Entry.TABLE_NAME, WHEEL_TYPE_LU_Entry.COLUMN_NAME_ID + " = ?",
                                where);
                        break;
                    default:
                    }
                } finally {
                    if (c != null)
                        c.close();
                    ScoutingDBHelper.getInstance().close();
                }
            }
        }
    } catch (JSONException e) {
        // TODO handle error
    }
}

From source file:org.frc836.database.DBSyncService.java

private void processConfig(JSONArray config) {
    try {/*  w ww  .j ava  2 s  .co  m*/
        for (int i = 0; i < config.length(); i++) {
            JSONObject row = config.getJSONObject(i);
            Action action = Action.UPDATE;
            if (row.getInt(CONFIGURATION_LU_Entry.COLUMN_NAME_INVALID) != 0) {
                action = Action.DELETE;
            }
            ContentValues vals = new ContentValues();
            vals.put(CONFIGURATION_LU_Entry.COLUMN_NAME_ID, row.getInt(CONFIGURATION_LU_Entry.COLUMN_NAME_ID));
            vals.put(CONFIGURATION_LU_Entry.COLUMN_NAME_CONFIGURATION_DESC,
                    row.getString(CONFIGURATION_LU_Entry.COLUMN_NAME_CONFIGURATION_DESC));
            vals.put(CONFIGURATION_LU_Entry.COLUMN_NAME_TIMESTAMP, DB.dateParser
                    .format(new Date(row.getLong(CONFIGURATION_LU_Entry.COLUMN_NAME_TIMESTAMP) * 1000)));

            // check if this entry exists already
            String[] projection = { CONFIGURATION_LU_Entry.COLUMN_NAME_CONFIGURATION_DESC };
            String[] where = { vals.getAsString(CONFIGURATION_LU_Entry.COLUMN_NAME_ID) };
            synchronized (ScoutingDBHelper.lock) {

                SQLiteDatabase db = ScoutingDBHelper.getInstance().getWritableDatabase();

                Cursor c = db.query(CONFIGURATION_LU_Entry.TABLE_NAME, projection, // select
                        CONFIGURATION_LU_Entry.COLUMN_NAME_ID + "=?", where, null, // don't
                        // group
                        null, // don't filter
                        null, // don't order
                        "0,1"); // limit to 1
                try {
                    if (!c.moveToFirst()) {
                        if (action == Action.UPDATE)
                            action = Action.INSERT;
                        else if (action == Action.DELETE)
                            action = Action.NOTHING;
                    }

                    switch (action) {
                    case UPDATE:
                        db.update(CONFIGURATION_LU_Entry.TABLE_NAME, vals,
                                CONFIGURATION_LU_Entry.COLUMN_NAME_ID + " = ?", where);
                        break;
                    case INSERT:
                        db.insert(CONFIGURATION_LU_Entry.TABLE_NAME, null, vals);
                        break;
                    case DELETE:
                        db.delete(CONFIGURATION_LU_Entry.TABLE_NAME,
                                CONFIGURATION_LU_Entry.COLUMN_NAME_ID + " = ?", where);
                        break;
                    default:
                    }
                } finally {
                    if (c != null)
                        c.close();
                    ScoutingDBHelper.getInstance().close();
                }
            }
        }
    } catch (JSONException e) {
        // TODO handle error
    }
}

From source file:org.ttrssreader.controllers.DBHelper.java

/**
 * remove specified mark in the temporary mark table for specified
 * articles and then cleanup this table//from   w  w w. ja v  a 2 s .  com
 *
 * @param ids  article IDs, which mark should be reseted
 * @param mark article mark to be reseted
 */
void setMarked(Map<Integer, String> ids, String mark) {
    if (!isDBAvailable())
        return;

    SQLiteDatabase db = getOpenHelper().getWritableDatabase();
    writeLock(true);
    db.beginTransaction();
    try {
        ContentValues cv = new ContentValues(1);
        for (String idList : StringSupport.convertListToString(ids.keySet(), 1000)) {
            cv.putNull(mark);
            db.update(TABLE_MARK, cv, "id IN(" + idList + ")", null);
            db.delete(TABLE_MARK, "isUnread IS null AND isStarred IS null AND isPublished IS null", null);
        }

        // Insert notes afterwards and only if given note is not null
        cv = new ContentValues(1);
        for (Integer id : ids.keySet()) {
            String note = ids.get(id);
            if (note == null || note.equals(""))
                continue;

            cv.put(MARK_NOTE, note);
            db.update(TABLE_MARK, cv, "id=" + id, null);
        }

        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
        writeLock(false);
    }
}

From source file:com.geecko.QuickLyric.tasks.WriteToDatabaseTask.java

@Override
public Boolean doInBackground(Object... params) {
    lyricsArray = new Lyrics[params.length - 2];
    SQLiteDatabase database;
    if (params[0] instanceof Fragment) {
        fragment = (Fragment) params[0];
        mContext = fragment.getActivity();
        if (mContext == null || !(mContext instanceof MainActivity))
            cancel(true);/*from   w  w  w  .j a v a2 s.c  om*/
        database = DatabaseHelper.getInstance(mContext).getWritableDatabase();
    } else
        database = (SQLiteDatabase) params[0];
    item = (MenuItem) params[1];
    if (params[2] instanceof Lyrics[])
        lyricsArray = (Lyrics[]) params[2];
    else
        for (int i = 0; i < lyricsArray.length; i++) {
            lyricsArray[i] = (Lyrics) params[i + 2];
        }
    boolean result = true;
    String[] columns = DatabaseHelper.columns;
    if (database != null && database.isOpen()) {
        database.beginTransaction();
        try {
            for (Lyrics lyrics : lyricsArray) {
                Lyrics storedLyrics = DatabaseHelper.getInstance(mContext)
                        .get(new String[] { lyrics.getArtist(), lyrics.getTitle(), lyrics.getOriginalArtist(),
                                lyrics.getOriginalTrack() });
                if ((storedLyrics == null || (!storedLyrics.isLRC() && lyrics.isLRC()))
                        && !"Storage".equals(lyrics.getSource())) {
                    ContentValues values = new ContentValues(2);
                    values.put(columns[0], lyrics.getArtist());
                    values.put(columns[1], lyrics.getTitle());
                    values.put(columns[2], lyrics.getText());
                    values.put(columns[3], lyrics.getURL());
                    values.put(columns[4], lyrics.getSource());
                    if (lyrics.getCoverURL() != null && lyrics.getCoverURL().startsWith("http://"))
                        values.put(columns[5], lyrics.getCoverURL());
                    values.put(columns[6], lyrics.getOriginalArtist());
                    values.put(columns[7], lyrics.getOriginalTrack());
                    values.put(columns[8], lyrics.isLRC() ? 1 : 0);
                    values.put(columns[9], lyrics.getWriter());
                    values.put(columns[10], lyrics.getCopyright());
                    database.delete(DatabaseHelper.TABLE_NAME,
                            String.format("%s=? AND %s=?", columns[0], columns[1]),
                            new String[] { lyrics.getArtist(), lyrics.getTitle() });
                    database.insert(DatabaseHelper.TABLE_NAME, null, values);
                    if (fragment instanceof LyricsViewFragment)
                        ((LyricsViewFragment) fragment).lyricsPresentInDB = true;
                    result = true;
                } else if (mContext != null) { // if called from activity, not service
                    database.delete(DatabaseHelper.TABLE_NAME,
                            String.format("%s=? AND %s=?", columns[0], columns[1]),
                            new String[] { lyrics.getArtist(), lyrics.getTitle() });
                    if (fragment instanceof LyricsViewFragment)
                        ((LyricsViewFragment) fragment).lyricsPresentInDB = false;
                    result = false;
                }
                database.yieldIfContendedSafely();
            }
            database.setTransactionSuccessful();
        } finally {
            database.endTransaction();
        }
    }
    return result;
}

From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java

private void rawDeleteDataInDBTable(SQLiteDatabase db, String tableId, String whereClause, String[] whereArgs) {
    boolean dbWithinTransaction = db.inTransaction();
    try {//from  ww  w.j a  v a2 s .c  om
        if (!dbWithinTransaction) {
            db.beginTransaction();
        }

        db.delete(tableId, whereClause, whereArgs);

        if (!dbWithinTransaction) {
            db.setTransactionSuccessful();
        }
    } finally {
        if (!dbWithinTransaction) {
            db.endTransaction();
        }
    }
}

From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java

/**
 * Insert or update a list of table-level metadata KVS entries. If clear is
 * true, then delete the existing set of values for this tableId before
 * inserting the new values.//w  w  w.  j a  v  a2  s . c om
 * 
 * @param db
 * @param tableId
 * @param metadata
 *          a List<KeyValueStoreEntry>
 * @param clear
 *          if true then delete the existing set of values for this tableId
 *          before inserting the new ones.
 */
public void replaceDBTableMetadata(SQLiteDatabase db, String tableId, List<KeyValueStoreEntry> metadata,
        boolean clear) {

    boolean dbWithinTransaction = db.inTransaction();
    try {
        if (!dbWithinTransaction) {
            db.beginTransaction();
        }

        if (clear) {
            db.delete(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME, KeyValueStoreColumns.TABLE_ID + "=?",
                    new String[] { tableId });
        }
        for (KeyValueStoreEntry e : metadata) {
            ContentValues values = new ContentValues();
            if (!tableId.equals(e.tableId)) {
                throw new IllegalArgumentException(
                        "updateDBTableMetadata: expected all kvs entries to share the same tableId");
            }
            if (e.value == null || e.value.trim().length() == 0) {
                deleteDBTableMetadata(db, e.tableId, e.partition, e.aspect, e.key);
            } else {
                values.put(KeyValueStoreColumns.TABLE_ID, e.tableId);
                values.put(KeyValueStoreColumns.PARTITION, e.partition);
                values.put(KeyValueStoreColumns.ASPECT, e.aspect);
                values.put(KeyValueStoreColumns.KEY, e.key);
                values.put(KeyValueStoreColumns.VALUE_TYPE, e.type);
                values.put(KeyValueStoreColumns.VALUE, e.value);
                db.replace(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME, null, values);
            }
        }

        if (!dbWithinTransaction) {
            db.setTransactionSuccessful();
        }
    } finally {
        if (!dbWithinTransaction) {
            db.endTransaction();
        }
    }
}

From source file:com.jefftharris.passwdsafe.NotificationMgr.java

/** Update the notification expirations for a password file */
private void doUpdatePasswdFileData(long uriId, PasswdFileData fileData, SQLiteDatabase db)
        throws SQLException {
    PasswdSafeUtil.dbginfo(TAG, "Update %s, id: %d", fileData.getUri(), uriId);

    TreeMap<ExpiryEntry, Long> entries = new TreeMap<>();
    Cursor cursor = db.query(DB_TABLE_EXPIRYS,
            new String[] { DB_COL_EXPIRYS_ID, DB_COL_EXPIRYS_UUID, DB_COL_EXPIRYS_TITLE, DB_COL_EXPIRYS_GROUP,
                    DB_COL_EXPIRYS_EXPIRE },
            DB_MATCH_EXPIRYS_URI, new String[] { Long.toString(uriId) }, null, null, null);
    try {/*from  ww w.  j ava2s  . c o m*/
        while (cursor.moveToNext()) {
            ExpiryEntry entry = new ExpiryEntry(cursor.getString(1), cursor.getString(2), cursor.getString(3),
                    cursor.getLong(4));
            entries.put(entry, cursor.getLong(0));
        }
    } finally {
        cursor.close();
    }

    boolean dbchanged = false;
    ContentValues values = null;
    for (PasswdRecord rec : fileData.getPasswdRecords()) {
        PasswdExpiration expiry = rec.getPasswdExpiry();
        if (expiry == null) {
            continue;
        }

        PwsRecord pwsrec = rec.getRecord();
        ExpiryEntry entry = new ExpiryEntry(rec.getUUID(), fileData.getTitle(pwsrec), fileData.getGroup(pwsrec),
                expiry.itsExpiration.getTime());
        if (entries.remove(entry) == null) {
            if (values == null) {
                values = new ContentValues();
                values.put(DB_COL_EXPIRYS_URI, uriId);
            }
            values.put(DB_COL_EXPIRYS_UUID, entry.itsUuid);
            values.put(DB_COL_EXPIRYS_TITLE, entry.itsTitle);
            values.put(DB_COL_EXPIRYS_GROUP, entry.itsGroup);
            values.put(DB_COL_EXPIRYS_EXPIRE, entry.itsExpiry);
            db.insertOrThrow(DB_TABLE_EXPIRYS, null, values);
            dbchanged = true;
        }
    }

    for (Long rmId : entries.values()) {
        db.delete(DB_TABLE_EXPIRYS, DB_MATCH_EXPIRYS_ID, new String[] { rmId.toString() });
        dbchanged = true;
    }

    if (dbchanged) {
        loadEntries(db);
    }
}

From source file:org.frc836.database.DBSyncService.java

private void processPits(JSONArray pits) {
    // TODO could be abstracted further
    try {// w w  w. j  a v a 2s  . co m
        for (int i = 0; i < pits.length(); i++) {
            JSONObject row = pits.getJSONObject(i);
            Action action = Action.UPDATE;
            if (row.getInt(PitStats.COLUMN_NAME_INVALID) != 0) {
                action = Action.DELETE;
            }
            ContentValues vals = PitStats.getNewPitStats().jsonToCV(row);

            // check if this entry exists already
            String[] projection = { PitStats.COLUMN_NAME_ID, PitStats.COLUMN_NAME_INVALID };
            String[] where = { vals.getAsString(PitStats.COLUMN_NAME_TEAM_ID) };

            synchronized (ScoutingDBHelper.lock) {

                SQLiteDatabase db = ScoutingDBHelper.getInstance().getWritableDatabase();

                Cursor c = db.query(PitStats.TABLE_NAME, projection, // select
                        PitStats.COLUMN_NAME_TEAM_ID + "=?", where, null, // don't
                        // group
                        null, // don't filter
                        null, // don't order
                        "0,1"); // limit to 1
                try {
                    if (!c.moveToFirst()) {
                        if (action == Action.UPDATE)
                            action = Action.INSERT;
                        else if (action == Action.DELETE)
                            action = Action.NOTHING;
                    } else {
                        int invalid = c.getInt(c.getColumnIndexOrThrow(PitStats.COLUMN_NAME_INVALID));
                        if (invalid > 0) // Current entry has not been sent
                                         // to server, don't overwrite
                            action = Action.NOTHING;
                    }

                    switch (action) {
                    case UPDATE:
                        db.update(PitStats.TABLE_NAME, vals, PitStats.COLUMN_NAME_TEAM_ID + " = ?", where);
                        break;
                    case INSERT:
                        db.insert(PitStats.TABLE_NAME, null, vals);
                        break;
                    case DELETE:
                        db.delete(PitStats.TABLE_NAME, PitStats.COLUMN_NAME_TEAM_ID + " = ?", where);
                        break;
                    default:
                    }
                } finally {
                    if (c != null)
                        c.close();
                    ScoutingDBHelper.getInstance().close();
                }
            }
        }
    } catch (JSONException e) {
        // TODO handle error
    }
}

From source file:org.pixmob.freemobile.netstat.SyncService.java

private void run(Intent intent, final SQLiteDatabase db) throws Exception {
    final long now = dateAtMidnight(System.currentTimeMillis());

    Log.i(TAG, "Initializing statistics before uploading");

    final LongSparseArray<DailyStat> stats = new LongSparseArray<DailyStat>(15);
    final Set<Long> uploadedStats = new HashSet<Long>(15);
    final long statTimestampStart = now - 7 * DAY_IN_MILLISECONDS;

    // Get pending uploads.
    Cursor c = db.query("daily_stat", new String[] { "stat_timestamp", "orange", "free_mobile", "sync" },
            "stat_timestamp>=? AND stat_timestamp<?",
            new String[] { String.valueOf(statTimestampStart), String.valueOf(now) }, null, null, null);
    try {// ww w.  j  a v  a  2 s .c  om
        while (c.moveToNext()) {
            final long d = c.getLong(0);
            final int sync = c.getInt(3);
            if (SYNC_UPLOADED == sync) {
                uploadedStats.add(d);
            } else if (SYNC_PENDING == sync) {
                final DailyStat s = new DailyStat();
                s.orange = c.getInt(1);
                s.freeMobile = c.getInt(2);
                stats.put(d, s);
            }
        }
    } finally {
        c.close();
    }

    // Compute missing uploads.
    final ContentValues cv = new ContentValues();
    db.beginTransaction();
    try {
        for (long d = statTimestampStart; d < now; d += DAY_IN_MILLISECONDS) {
            if (stats.get(d) == null && !uploadedStats.contains(d)) {
                final DailyStat s = computeDailyStat(d);
                cv.put("stat_timestamp", d);
                cv.put("orange", s.orange);
                cv.put("free_mobile", s.freeMobile);
                cv.put("sync", SYNC_PENDING);
                db.insertOrThrow("daily_stat", null, cv);
                stats.put(d, s);
            }
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }

    // Delete old statistics.
    if (DEBUG) {
        Log.d(TAG, "Cleaning up upload database");
    }
    db.delete("daily_stat", "stat_timestamp<?", new String[] { String.valueOf(statTimestampStart) });

    // Check if there are any statistics to upload.
    final int statsLen = stats.size();
    if (statsLen == 0) {
        Log.i(TAG, "Nothing to upload");
        return;
    }

    // Check if the remote server is up.
    final HttpClient client = createHttpClient();
    try {
        client.head(createServerUrl(null)).execute();
    } catch (HttpClientException e) {
        Log.w(TAG, "Remote server is not available: cannot upload statistics", e);
        return;
    }

    // Upload statistics.
    Log.i(TAG, "Uploading statistics");
    final JSONObject json = new JSONObject();
    final String deviceId = getDeviceId();
    final boolean deviceWasRegistered = intent.getBooleanExtra(EXTRA_DEVICE_REG, false);
    for (int i = 0; i < statsLen; ++i) {
        final long d = stats.keyAt(i);
        final DailyStat s = stats.get(d);

        try {
            json.put("timeOnOrange", s.orange);
            json.put("timeOnFreeMobile", s.freeMobile);
        } catch (JSONException e) {
            final IOException ioe = new IOException("Failed to prepare statistics upload");
            ioe.initCause(e);
            throw ioe;
        }

        final String url = createServerUrl(
                "/device/" + deviceId + "/daily/" + DateFormat.format("yyyyMMdd", d));
        if (DEBUG) {
            Log.d(TAG, "Uploading statistics for " + DateUtils.formatDate(d) + " to: " + url);
        }

        final byte[] rawJson = json.toString().getBytes("UTF-8");
        try {
            client.post(url).content(rawJson, "application/json")
                    .expect(HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_NOT_FOUND)
                    .to(new HttpResponseHandler() {
                        @Override
                        public void onResponse(HttpResponse response) throws Exception {
                            final int sc = response.getStatusCode();
                            if (HttpURLConnection.HTTP_NOT_FOUND == sc) {
                                // Check if the device has just been
                                // registered.
                                if (deviceWasRegistered) {
                                    throw new IOException("Failed to upload statistics");
                                } else {
                                    // Got 404: the device does not exist.
                                    // We need to register this device.
                                    registerDevice(deviceId);

                                    // Restart this service.
                                    startService(new Intent(getApplicationContext(), SyncService.class)
                                            .putExtra(EXTRA_DEVICE_REG, true));
                                }
                            } else if (HttpURLConnection.HTTP_OK == sc) {
                                // Update upload database.
                                cv.clear();
                                cv.put("sync", SYNC_UPLOADED);
                                db.update("daily_stat", cv, "stat_timestamp=?",
                                        new String[] { String.valueOf(d) });

                                if (DEBUG) {
                                    Log.d(TAG, "Upload done for " + DateUtils.formatDate(d));
                                }
                            }
                        }
                    }).execute();
        } catch (HttpClientException e) {
            final IOException ioe = new IOException("Failed to send request with statistics");
            ioe.initCause(e);
            throw ioe;
        }
    }
}