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.opendatakit.common.android.utilities.ODKDatabaseUtils.java

/**
 * Update all rows for the given rowId to SavepointType 'INCOMPLETE' and
 * remove all but the most recent row. When used with a rowId that has
 * checkpoints, this updates to the most recent checkpoint and removes any
 * earlier checkpoints, incomplete or complete savepoints. Otherwise, it has
 * the general effect of resetting the rowId to an INCOMPLETE state.
 * /*from  w w  w  .  j a  va  2s  .c o m*/
 * @param db
 * @param tableId
 * @param rowId
 */
public void saveAsIncompleteMostRecentCheckpointDataInDBTableWithId(SQLiteDatabase db, String tableId,
        String rowId) {
    boolean dbWithinTransaction = db.inTransaction();
    try {
        if (!dbWithinTransaction) {
            db.beginTransaction();
        }

        db.execSQL(
                "UPDATE \"" + tableId + "\" SET " + DataTableColumns.SAVEPOINT_TYPE + "= ? WHERE "
                        + DataTableColumns.ID + "=?",
                new String[] { SavepointTypeManipulator.incomplete(), rowId });
        db.delete(tableId,
                DataTableColumns.ID + "=? AND " + DataTableColumns.SAVEPOINT_TIMESTAMP + " NOT IN (SELECT MAX("
                        + DataTableColumns.SAVEPOINT_TIMESTAMP + ") FROM \"" + tableId + "\" WHERE "
                        + DataTableColumns.ID + "=?)",
                new String[] { rowId, rowId });

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

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

/**
 * Delete the specified rowId in this tableId. Deletion respects sync
 * semantics. If the row is in the SyncState.new_row state, then the row and
 * its associated file attachments are immediately deleted. Otherwise, the row
 * is placed into the SyncState.deleted state and will be retained until the
 * device can delete the record on the server.
 * <p>/*w w  w.j a v a 2  s  .c o  m*/
 * If you need to immediately delete a record that would otherwise sync to the
 * server, call updateRowETagAndSyncState(...) to set the row to
 * SyncState.new_row, and then call this method and it will be immediately
 * deleted (in this case, unless the record on the server was already deleted,
 * it will remain and not be deleted during any subsequent synchronizations).
 * 
 * @param db
 * @param appName
 * @param tableId
 * @param rowId
 */
public void deleteDataInExistingDBTableWithId(SQLiteDatabase db, String appName, String tableId, String rowId) {
    SyncState syncState = getSyncState(db, appName, tableId, rowId);

    boolean dbWithinTransaction = db.inTransaction();
    if (syncState == SyncState.new_row) {
        String[] whereArgs = { rowId };
        String whereClause = DataTableColumns.ID + " = ?";

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

            db.delete(tableId, whereClause, whereArgs);

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

        File instanceFolder = new File(ODKFileUtils.getInstanceFolder(appName, tableId, rowId));
        try {
            FileUtils.deleteDirectory(instanceFolder);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            WebLogger.getLogger(appName).e(t,
                    "Unable to delete this directory: " + instanceFolder.getAbsolutePath());
            WebLogger.getLogger(appName).printStackTrace(e);
        }
    } else if (syncState == SyncState.synced || syncState == SyncState.changed) {
        String[] whereArgs = { rowId };
        ContentValues values = new ContentValues();
        values.put(DataTableColumns.SYNC_STATE, SyncState.deleted.name());
        values.put(DataTableColumns.SAVEPOINT_TIMESTAMP,
                TableConstants.nanoSecondsFromMillis(System.currentTimeMillis()));
        try {
            if (!dbWithinTransaction) {
                db.beginTransaction();
            }

            db.update(tableId, values, DataTableColumns.ID + " = ?", whereArgs);

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

From source file:com.odoo.orm.OModel.java

/**
 * Manage many to many records.//from w  w w . ja va  2s.c  om
 * 
 * @param db
 *            the db
 * @param rel_model
 *            the rel_model
 * @param ids
 *            the ids
 * @param base_id
 *            the base_id
 * @param command
 *            the command
 */
public void manageManyToManyRecords(SQLiteDatabase db, OModel rel_model, List<Integer> ids, Integer base_id,
        Command command) {
    String table = getTableName() + "_" + rel_model.getTableName() + "_rel";
    String base_column = getTableName() + "_id";
    String rel_column = rel_model.getTableName() + "_id";

    switch (command) {
    case Add:
        // Adding records to relation model
        if (ids.size() > 0) {
            for (int id : ids) {
                ContentValues values = new ContentValues();
                values.put(base_column, base_id);
                values.put(rel_column, id);
                values.put("odoo_name", mUser.getAndroidName());
                values.put("local_write_date", ODate.getDate());
                db.insert(table, null, values);
            }
        }
        break;
    case Update:
        break;
    case Delete:
        // Deleting records to relation model
        if (ids.size() > 0) {
            for (int id : ids) {
                db.delete(table, base_column + " = ? AND  " + rel_column + " = ?",
                        new String[] { base_id + "", id + "" });
            }
        }
        break;
    case Replace:
        // Removing old entries
        String where = base_column + " = ? ";
        String[] args = new String[] { base_id + "" };
        db.delete(table, getWhereClause(where), getWhereArgs(where, args));
        // Creating new entries
        manageManyToManyRecords(db, rel_model, ids, base_id, Command.Add);
        break;
    }
}

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

/**
 * Deletes the server conflict row (if any) for this rowId in this tableId.
 * /*from   ww  w  .  j av  a 2  s . c om*/
 * @param db
 * @param tableId
 * @param rowId
 */
public void deleteServerConflictRowWithId(SQLiteDatabase db, String tableId, String rowId) {
    // delete the old server-values in_conflict row if it exists
    String whereClause = String.format("%s = ? AND %s = ? AND %s IN " + "( ?, ? )", DataTableColumns.ID,
            DataTableColumns.SYNC_STATE, DataTableColumns.CONFLICT_TYPE);
    String[] whereArgs = { rowId, SyncState.in_conflict.name(),
            String.valueOf(ConflictType.SERVER_DELETED_OLD_VALUES),
            String.valueOf(ConflictType.SERVER_UPDATED_UPDATED_VALUES) };

    boolean dbWithinTransaction = db.inTransaction();
    try {
        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

/**
 * Drop the given tableId and remove all the files (both configuration and
 * data attachments) associated with that table.
 * /*from w  w w .  ja  v a  2 s.  com*/
 * @param db
 * @param appName
 * @param tableId
 */
public void deleteDBTableAndAllData(SQLiteDatabase db, final String appName, final String tableId) {

    SyncETagsUtils seu = new SyncETagsUtils();
    boolean dbWithinTransaction = db.inTransaction();
    try {
        String whereClause = TableDefinitionsColumns.TABLE_ID + " = ?";
        String[] whereArgs = { tableId };

        if (!dbWithinTransaction) {
            db.beginTransaction();
        }

        // Drop the table used for the formId
        db.execSQL("DROP TABLE IF EXISTS \"" + tableId + "\";");

        // Delete the server sync ETags associated with this table
        seu.deleteAllSyncETags(db, tableId);

        // Delete the table definition for the tableId
        int count = db.delete(DatabaseConstants.TABLE_DEFS_TABLE_NAME, whereClause, whereArgs);

        // Delete the column definitions for this tableId
        db.delete(DatabaseConstants.COLUMN_DEFINITIONS_TABLE_NAME, whereClause, whereArgs);

        // Delete the uploads for the tableId
        String uploadWhereClause = InstanceColumns.DATA_TABLE_TABLE_ID + " = ?";
        db.delete(DatabaseConstants.UPLOADS_TABLE_NAME, uploadWhereClause, whereArgs);

        // Delete the values from the 4 key value stores
        db.delete(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME, whereClause, whereArgs);
        db.delete(DatabaseConstants.KEY_VALULE_STORE_SYNC_TABLE_NAME, whereClause, whereArgs);

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

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

    // And delete the files from the SDCard...
    String tableDir = ODKFileUtils.getTablesFolder(appName, tableId);
    try {
        FileUtils.deleteDirectory(new File(tableDir));
    } catch (IOException e1) {
        e1.printStackTrace();
        throw new IllegalStateException("Unable to delete the " + tableDir + " directory", e1);
    }

    String assetsCsvDir = ODKFileUtils.getAssetsFolder(appName) + "/csv";
    try {
        Collection<File> files = FileUtils.listFiles(new File(assetsCsvDir), new IOFileFilter() {

            @Override
            public boolean accept(File file) {
                String[] parts = file.getName().split("\\.");
                return (parts[0].equals(tableId) && parts[parts.length - 1].equals("csv")
                        && (parts.length == 2 || parts.length == 3
                                || (parts.length == 4 && parts[parts.length - 2].equals("properties"))));
            }

            @Override
            public boolean accept(File dir, String name) {
                String[] parts = name.split("\\.");
                return (parts[0].equals(tableId) && parts[parts.length - 1].equals("csv")
                        && (parts.length == 2 || parts.length == 3
                                || (parts.length == 4 && parts[parts.length - 2].equals("properties"))));
            }
        }, new IOFileFilter() {

            // don't traverse into directories
            @Override
            public boolean accept(File arg0) {
                return false;
            }

            // don't traverse into directories
            @Override
            public boolean accept(File arg0, String arg1) {
                return false;
            }
        });

        FileUtils.deleteDirectory(new File(tableDir));
        for (File f : files) {
            FileUtils.deleteQuietly(f);
        }
    } catch (IOException e1) {
        e1.printStackTrace();
        throw new IllegalStateException("Unable to delete the " + tableDir + " directory", e1);
    }
}

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

private void processMatches(JSONArray matches) {
    // TODO could be abstracted further
    try {/*w  w w. j av  a  2 s  . c  o m*/
        for (int i = 0; i < matches.length(); i++) {
            JSONObject row = matches.getJSONObject(i);
            Action action = Action.UPDATE;
            if (row.getInt(MatchStatsStruct.COLUMN_NAME_INVALID) != 0) {
                action = Action.DELETE;
            }
            ContentValues vals = MatchStatsStruct.getNewMatchStats().jsonToCV(row);

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

            synchronized (ScoutingDBHelper.lock) {
                SQLiteDatabase db = ScoutingDBHelper.getInstance().getWritableDatabase();

                Cursor c = db.query(MatchStatsStruct.TABLE_NAME, projection, // select
                        MatchStatsStruct.COLUMN_NAME_EVENT_ID + "=? AND "
                                + MatchStatsStruct.COLUMN_NAME_MATCH_ID + "=? AND "
                                + MatchStatsStruct.COLUMN_NAME_TEAM_ID + "=? AND "
                                + MatchStatsStruct.COLUMN_NAME_PRACTICE_MATCH + "=?",
                        where, null, // don't
                        // group
                        null, // don't filter
                        null, // don't order
                        "0,1"); // limit to 1
                try {
                    int id = 0, invalid = 0;
                    if (!c.moveToFirst()) {
                        if (action == Action.UPDATE)
                            action = Action.INSERT;
                        else if (action == Action.DELETE)
                            action = Action.NOTHING;
                    } else {
                        id = c.getInt(c.getColumnIndexOrThrow(MatchStatsStruct.COLUMN_NAME_ID));
                        invalid = c.getInt(c.getColumnIndexOrThrow(MatchStatsStruct.COLUMN_NAME_INVALID));
                        if (invalid > 0) // this field has not been sent to
                                         // server yet.
                            action = Action.NOTHING;
                    }

                    String[] where2 = { String.valueOf(id) };

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

From source file:org.opendatakit.common.android.provider.impl.InstanceProviderImpl.java

/**
 * This method removes the entry from the content provider, and also removes
 * any associated files. files: form.xml, [formmd5].formdef, formname
 * {directory}/*from  w w  w.  j a v a 2  s  .  c  o m*/
 */
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() < 2 || segments.size() > 3) {
        throw new SQLException("Unknown URI (too many segments!) " + uri);
    }

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    String tableId = segments.get(1);
    // _ID in UPLOADS_TABLE_NAME
    String instanceId = (segments.size() == 3 ? segments.get(2) : null);

    SQLiteDatabase db = null;
    List<IdStruct> idStructs = new ArrayList<IdStruct>();
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();

        boolean success = false;
        try {
            success = ODKDatabaseUtils.get().hasTableId(db, tableId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SQLException("Unknown URI (exception testing for tableId) " + uri);
        }
        if (!success) {
            throw new SQLException("Unknown URI (missing data table for tableId) " + uri);
        }

        String dbTableName = "\"" + tableId + "\"";

        if (segments.size() == 2) {
            where = "(" + where + ") AND (" + InstanceColumns.DATA_INSTANCE_ID + "=? )";
            if (whereArgs != null) {
                String[] args = new String[whereArgs.length + 1];
                for (int i = 0; i < whereArgs.length; ++i) {
                    args[i] = whereArgs[i];
                }
                args[whereArgs.length] = instanceId;
                whereArgs = args;
            } else {
                whereArgs = new String[] { instanceId };
            }
        }

        Cursor del = null;
        try {
            del = this.query(uri, null, where, whereArgs, null);
            del.moveToPosition(-1);
            while (del.moveToNext()) {
                String iId = ODKDatabaseUtils.get().getIndexAsString(del,
                        del.getColumnIndex(InstanceColumns._ID));
                String iIdDataTable = ODKDatabaseUtils.get().getIndexAsString(del,
                        del.getColumnIndex(InstanceColumns.DATA_INSTANCE_ID));
                idStructs.add(new IdStruct(iId, iIdDataTable));
                String path = ODKFileUtils.getInstanceFolder(appName, tableId, iIdDataTable);
                File f = new File(path);
                if (f.exists()) {
                    if (f.isDirectory()) {
                        FileUtils.deleteDirectory(f);
                    } else {
                        f.delete();
                    }
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new IllegalArgumentException("Unable to delete instance directory: " + e.toString());
        } finally {
            if (del != null) {
                del.close();
            }
        }

        for (IdStruct idStruct : idStructs) {
            db.delete(DatabaseConstants.UPLOADS_TABLE_NAME, InstanceColumns.DATA_INSTANCE_ID + "=?",
                    new String[] { idStruct.idUploadsTable });
            db.delete(dbTableName, DATA_TABLE_ID_COLUMN + "=?", new String[] { idStruct.idDataTable });
        }
        db.setTransactionSuccessful();
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return idStructs.size();
}

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

/**
 * The deletion filter includes all non-null arguments. If all arguments
 * (except the db) are null, then all properties are removed.
 * //from w  w w  .jav a  2  s  . co m
 * @param db
 * @param tableId
 * @param partition
 * @param aspect
 * @param key
 */
public void deleteDBTableMetadata(SQLiteDatabase db, String tableId, String partition, String aspect,
        String key) {

    StringBuilder b = new StringBuilder();
    ArrayList<String> selArgs = new ArrayList<String>();
    if (tableId != null) {
        b.append(KeyValueStoreColumns.TABLE_ID).append("=?");
        selArgs.add(tableId);
    }
    if (partition != null) {
        if (b.length() != 0) {
            b.append(" AND ");
        }
        b.append(KeyValueStoreColumns.PARTITION).append("=?");
        selArgs.add(partition);
    }
    if (aspect != null) {
        if (b.length() != 0) {
            b.append(" AND ");
        }
        b.append(KeyValueStoreColumns.ASPECT).append("=?");
        selArgs.add(aspect);
    }
    if (key != null) {
        if (b.length() != 0) {
            b.append(" AND ");
        }
        b.append(KeyValueStoreColumns.KEY).append("=?");
        selArgs.add(key);
    }

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

        db.delete(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME, b.toString(),
                selArgs.toArray(new String[selArgs.size()]));

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

From source file:com.example.android.lightcontrol.MainActivity.java

public void query_shortaddr() {
    helper = new DBHelper(getApplicationContext());
    cursor = helper.select(TABLE_NAME_SHORT_ADDRESS);
    int i;/*from   w ww .ja v  a  2s.  c  o m*/

    if (GlobalVariable.query_short_packet == null) {
        Toast.makeText(getApplicationContext(), "can't get the short address", Toast.LENGTH_SHORT).show();
    } else {
        SQLiteDatabase db = helper.getWritableDatabase();
        if (cursor.getCount() > 0) {
            db.delete(TABLE_NAME_SHORT_ADDRESS, null, null);
        }
        for (i = 14; i < GlobalVariable.query_short_packet.length(); i = i + 22) {
            ContentValues values = new ContentValues();
            values.put(FEILD_SHORTADDRESS, GlobalVariable.query_short_packet.substring(i, i + 4));
            db.insert(TABLE_NAME_SHORT_ADDRESS, null, values);
        }
        cursor.requery();
        //query_daliaddr();
        new Query_dali_Async().execute();
    }
    if (D)
        Log.e(TAG, "in querylight " + list);

}

From source file:org.pixmob.freemobile.netstat.SyncServiceTesting.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<>(15);
    final Set<Long> uploadedStats = new HashSet<>(15);
    final long statTimestampStart = now - 7 * DAY_IN_MILLISECONDS;

    // Get pending uploads.
    Cursor pendingUploadsCursor = null;
    try {/*  w  w w  . java 2s.c o  m*/
        pendingUploadsCursor = db.query("daily_stat_testing",
                new String[] { "stat_timestamp", "orange", "free_mobile", "free_mobile_3g", "free_mobile_4g",
                        "free_mobile_femtocell", "sync" },
                "stat_timestamp>=? AND stat_timestamp<?",
                new String[] { String.valueOf(statTimestampStart), String.valueOf(now) }, null, null, null);
        while (pendingUploadsCursor.moveToNext()) {
            final long d = pendingUploadsCursor.getLong(0);
            final int sync = pendingUploadsCursor.getInt(6);
            if (SYNC_UPLOADED == sync) {
                uploadedStats.add(d);
            } else if (SYNC_PENDING == sync) {
                final DailyStat s = new DailyStat();
                s.orange = pendingUploadsCursor.getInt(1);
                s.freeMobile = pendingUploadsCursor.getInt(2);
                s.freeMobile3G = pendingUploadsCursor.getInt(3);
                s.freeMobile4G = pendingUploadsCursor.getInt(4);
                s.freeMobileFemtocell = pendingUploadsCursor.getInt(5);
                stats.put(d, s);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    } finally {
        try {
            if (pendingUploadsCursor != null)
                pendingUploadsCursor.close();
        } catch (Exception e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    }

    // 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("free_mobile_3g", s.freeMobile3G);
                cv.put("free_mobile_4g", s.freeMobile4G);
                cv.put("free_mobile_femtocell", s.freeMobileFemtocell);
                cv.put("sync", SYNC_PENDING);
                db.insertOrThrow("daily_stat_testing", 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_testing", "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);
            json.put("timeOnFreeMobile3g", s.freeMobile3G);
            json.put("timeOnFreeMobile4g", s.freeMobile4G);
            json.put("timeOnFreeMobileFemtocell", s.freeMobileFemtocell);
        } 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(), SyncServiceTesting.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_testing", 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;
        }
    }
}