Example usage for android.database.sqlite SQLiteDatabase update

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

Introduction

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

Prototype

public int update(String table, ContentValues values, String whereClause, String[] whereArgs) 

Source Link

Document

Convenience method for updating rows in the database.

Usage

From source file:com.rener.sea.DBHelper.java

private long setSyncSpecialization(JSONArray data) {
    SQLiteDatabase db = this.getWritableDatabase();
    int i = -1;//from w  w  w . j  a v  a2 s .  c  o  m
    try {
        for (i = 0; i < data.length(); i++) {
            JSONObject item = data.getJSONObject(i);
            ContentValues values = new ContentValues();
            values.put(DBSchema.MODIFIED, DBSchema.MODIFIED_NO);
            db.update(DBSchema.TABLE_SPECIALIZATION, values, DBSchema.SPECIALIZATION_ID + " =? ",
                    new String[] { String.valueOf(item.getLong(DBSchema.SPECIALIZATION_ID)) });
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    db.close();
    return i;

}

From source file:com.rener.sea.DBHelper.java

private long setSyncDevices(JSONArray data) {
    SQLiteDatabase db = this.getWritableDatabase();
    int i = -1;/*w w w . ja  va2  s .c o  m*/
    try {
        for (i = 0; i < data.length(); i++) {
            JSONObject item = data.getJSONObject(i);
            ContentValues values = new ContentValues();
            values.put(DBSchema.MODIFIED, DBSchema.MODIFIED_NO);
            db.update(DBSchema.TABLE_DEVICES, values, DBSchema.DEVICE_ID + " =? ",
                    new String[] { String.valueOf(item.getLong(DBSchema.DEVICE_ID)) });

        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    db.close();
    return i;
}

From source file:com.rener.sea.DBHelper.java

private long setSyncPath(JSONArray data) {
    SQLiteDatabase db = this.getWritableDatabase();
    int i = -1;/*from  ww w.j  a  v  a  2s  .  com*/
    try {
        for (i = 0; i < data.length(); i++) {
            JSONObject item = data.getJSONObject(i);
            ContentValues values = new ContentValues();
            values.put(DBSchema.MODIFIED, DBSchema.MODIFIED_NO);
            db.update(DBSchema.TABLE_PATH, values,
                    DBSchema.PATH_REPORT_ID + " =? AND " + DBSchema.PATH_OPTION_ID + " =? ",
                    new String[] { String.valueOf(item.getLong(DBSchema.PATH_REPORT_ID)),
                            String.valueOf(item.getLong(DBSchema.PATH_OPTION_ID)) });
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    db.close();
    return i;
}

From source file:com.rener.sea.DBHelper.java

private long setSyncUsers_specialization(JSONArray data) {
    SQLiteDatabase db = this.getWritableDatabase();
    int i = -1;/*from  w  ww  .ja  v  a  2 s .c om*/
    try {
        for (i = 0; i < data.length(); i++) {
            JSONObject item = data.getJSONObject(i);
            ContentValues values = new ContentValues();
            values.put(DBSchema.MODIFIED, DBSchema.MODIFIED_NO);
            db.update(DBSchema.TABLE_USERS_SPECIALIZATION, values,
                    DBSchema.USERS_SPECIALIZATION_USER_ID + " =? AND "
                            + DBSchema.USERS_SPECIALIZATION_SPECIALIZATION_ID + " =? ",
                    new String[] { String.valueOf(item.getLong(DBSchema.USERS_SPECIALIZATION_USER_ID)),
                            String.valueOf(item.getLong(DBSchema.USERS_SPECIALIZATION_SPECIALIZATION_ID)) });
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    db.close();
    return -1;
}

From source file:com.rener.sea.DBHelper.java

private long setSyncLocation_category(JSONArray data) {
    SQLiteDatabase db = this.getWritableDatabase();
    int i = -1;/*ww w.  ja v a2  s  .c  o  m*/
    try {
        for (i = 0; i < data.length(); i++) {
            JSONObject item = data.getJSONObject(i);
            ContentValues values = new ContentValues();
            values.put(DBSchema.MODIFIED, DBSchema.MODIFIED_NO);
            db.update(DBSchema.TABLE_LOCATION_CATEGORY, values,
                    DBSchema.LOCATION_CATEGORY_LOCATION_ID + " =? AND " + DBSchema.LOCATION_CATEGORY_CATEGORY_ID
                            + " =? ",
                    new String[] { String.valueOf(item.getLong(DBSchema.LOCATION_CATEGORY_LOCATION_ID)),
                            String.valueOf(item.getLong(DBSchema.LOCATION_CATEGORY_CATEGORY_ID)) });
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    db.close();
    return i;
}

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>//from   ww  w  .  j  a  va  2s. 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.openatk.planting.MainActivity.java

@Override
public void EditJobSave(Job job, Boolean changeState, Boolean unselect) {
    currentJob = job;/*from   ww w  .  ja  v a2 s  . c o m*/

    if (unselect && this.currentPolygon != null) {
        this.currentPolygon.unselect();
    }
    if (job != null && job.getStatus() != Job.STATUS_NOT_PLANNED) {
        // Save new job in db
        SQLiteDatabase database = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(TableJobs.COL_WORKER_NAME, job.getWorkerName());
        values.put(TableJobs.COL_SEED_NAME, job.getSeedName());
        if (currentField == null) {
            values.put(TableJobs.COL_FIELD_NAME, currentJob.getFieldName());
        } else {
            values.put(TableJobs.COL_FIELD_NAME, currentField.getName());
        }
        values.put(TableJobs.COL_STATUS, job.getStatus());
        values.put(TableJobs.COL_COMMENTS, job.getComments());
        values.put(TableJobs.COL_SEEDNOTES, job.getSeednotes());
        values.put(TableJobs.COL_DATE_OF_OPERATION, job.getDateOfOperation());
        values.put(TableJobs.COL_HAS_CHANGED, job.getHasChanged());
        values.put(TableJobs.COL_DATE_CHANGED, job.getDateChanged());
        values.put(TableJobs.COL_OPERATION_ID, currentOperationId);

        if (job.getId() == null) {
            Integer insertId = (int) database.insert(TableJobs.TABLE_NAME, null, values);
            currentJob.setId(insertId);
            if (job.getWorkerName().isEmpty() == false) {
                // Save this choice in preferences for next open
                SharedPreferences prefs = PreferenceManager
                        .getDefaultSharedPreferences(getApplicationContext());
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString("WorkerName", job.getWorkerName());
                editor.commit();
            }
            if (job.getSeedName().isEmpty() == false) {
                // Save this choice in preferences for next open
                SharedPreferences prefs = PreferenceManager
                        .getDefaultSharedPreferences(getApplicationContext());
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString("SeedName", job.getSeedName());
                editor.commit();
            }
            Log.d("MainActivity - EditJobSave", "Adding new job to db:" + job.getFieldName() + " - Field Id:"
                    + Integer.toString(insertId) + ", Op Id:" + currentOperationId);
        } else {
            // Update job
            String where = TableJobs.COL_ID + " = " + job.getId() + " AND " + TableJobs.COL_DELETED + " = 0";
            ;
            database.update(TableJobs.TABLE_NAME, values, where, null);
            Log.d("MainActivity - EditJobSave", "Updating job in db:" + job.getFieldName() + " - Field Id:"
                    + Integer.toString(job.getId()) + ", Op Id:" + currentOperationId);
        }

        //Add notes to notes table
        List<Note> notes = currentJob.getNotes();
        Log.d("MainActivity - EditJobSave", "Number of notes: " + Integer.toString(notes.size()));
        for (int i = 0; i < notes.size(); i++) {
            Note toadd = notes.get(i);
            ContentValues values2 = new ContentValues();
            values2.put(TableNotes.COL_TOPIC, toadd.getTopic());
            values2.put(TableNotes.COL_COMMENT, toadd.getComment());
            values2.put(TableNotes.COL_FIELD_NAME, currentJob.getFieldName());
            if (toadd.getId() == null) {
                //New note, no id
                Integer newNoteId = (int) database.insert(TableNotes.TABLE_NAME, null, values2);
                toadd.setId(newNoteId);
                Log.d("MainActivity - EditJobSave", "Inserted new note in db");
            } else {
                //Update this note in the db
                String where2 = TableNotes.COL_ID + " = " + toadd.getId() + " AND " + TableNotes.COL_DELETED
                        + " = 0";
                database.update(TableNotes.TABLE_NAME, values2, where2, null);
                Log.d("MainActivity - EditJobSave", "Updated note comments");
            }
        }
        dbHelper.close();
        // Set fill according to status
        if (this.currentPolygon != null) {
            if (currentJob.getStatus() == Job.STATUS_NOT_PLANNED) {
                this.currentPolygon.setFillColor(Field.FILL_COLOR_NOT_PLANNED);
            } else if (currentJob.getStatus() == Job.STATUS_PLANNED) {
                this.currentPolygon.setFillColor(Field.FILL_COLOR_PLANNED);
            } else if (currentJob.getStatus() == Job.STATUS_STARTED) {
                this.currentPolygon.setFillColor(Field.FILL_COLOR_STARTED);
            } else if (currentJob.getStatus() == Job.STATUS_DONE) {
                this.currentPolygon.setFillColor(Field.FILL_COLOR_DONE);
            }
        }
    } else {
        currentJob = null;
    }
    if (changeState)
        hideEdit(true);

    if (unselect) {
        this.currentField = null;
        this.currentJob = null;
    }
    if (this.fragmentListView != null)
        this.fragmentListView.getData();

    this.trelloController.syncDelayed();
}

From source file:org.digitalcampus.oppia.application.DbHelper.java

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    if (oldVersion < 7) {
        db.execSQL("drop table if exists " + COURSE_TABLE);
        db.execSQL("drop table if exists " + ACTIVITY_TABLE);
        db.execSQL("drop table if exists " + TRACKER_LOG_TABLE);
        db.execSQL("drop table if exists " + QUIZATTEMPTS_TABLE);
        createCourseTable(db);//from   ww w  .j  a v  a2 s  . com
        createActivityTable(db);
        createLogTable(db);
        createQuizAttemptsTable(db);
        return;
    }

    if (oldVersion <= 7 && newVersion >= 8) {
        String sql = "ALTER TABLE " + ACTIVITY_TABLE + " ADD COLUMN " + ACTIVITY_C_STARTDATE
                + " datetime null;";
        db.execSQL(sql);
        sql = "ALTER TABLE " + ACTIVITY_TABLE + " ADD COLUMN " + ACTIVITY_C_ENDDATE + " datetime null;";
        db.execSQL(sql);
    }

    if (oldVersion <= 8 && newVersion >= 9) {
        String sql = "ALTER TABLE " + COURSE_TABLE + " ADD COLUMN " + COURSE_C_SCHEDULE + " int null;";
        db.execSQL(sql);
    }

    if (oldVersion <= 9 && newVersion >= 10) {
        String sql = "ALTER TABLE " + ACTIVITY_TABLE + " ADD COLUMN " + ACTIVITY_C_TITLE + " text null;";
        db.execSQL(sql);
    }

    // This is a fix as previous versions may not have upgraded db tables correctly
    if (oldVersion <= 10 && newVersion >= 11) {
        String sql1 = "ALTER TABLE " + ACTIVITY_TABLE + " ADD COLUMN " + ACTIVITY_C_STARTDATE
                + " datetime null;";
        String sql2 = "ALTER TABLE " + ACTIVITY_TABLE + " ADD COLUMN " + ACTIVITY_C_ENDDATE + " datetime null;";
        String sql3 = "ALTER TABLE " + COURSE_TABLE + " ADD COLUMN " + COURSE_C_SCHEDULE + " int null;";
        String sql4 = "ALTER TABLE " + ACTIVITY_TABLE + " ADD COLUMN " + ACTIVITY_C_TITLE + " text null;";
        try {
            db.execSQL(sql1);
        } catch (Exception e) {

        }
        try {
            db.execSQL(sql2);
        } catch (Exception e) {

        }
        try {
            db.execSQL(sql3);
        } catch (Exception e) {

        }
        try {
            db.execSQL(sql4);
        } catch (Exception e) {

        }
    }

    if (oldVersion <= 11 && newVersion >= 12) {
        String sql = "ALTER TABLE " + COURSE_TABLE + " ADD COLUMN " + COURSE_C_LANGS + " text null;";
        db.execSQL(sql);
        sql = "ALTER TABLE " + COURSE_TABLE + " ADD COLUMN " + COURSE_C_IMAGE + " text null;";
        db.execSQL(sql);
    }

    if (oldVersion <= 12 && newVersion >= 13) {
        String sql = "ALTER TABLE " + TRACKER_LOG_TABLE + " ADD COLUMN " + TRACKER_LOG_C_COMPLETED
                + " integer default 0;";
        db.execSQL(sql);
    }
    // skip jump from 13 to 14
    if (oldVersion <= 14 && newVersion >= 15) {
        ContentValues values = new ContentValues();
        values.put(TRACKER_LOG_C_COMPLETED, true);
        db.update(TRACKER_LOG_TABLE, values, null, null);
    }

    if (oldVersion <= 15 && newVersion >= 16) {
        String sql = "ALTER TABLE " + COURSE_TABLE + " ADD COLUMN " + COURSE_C_DESC + " text null;";
        db.execSQL(sql);
    }

    if (oldVersion <= 16 && newVersion >= 17) {
        String sql = "ALTER TABLE " + COURSE_TABLE + " ADD COLUMN " + COURSE_C_ORDER_PRIORITY
                + " integer default 0;";
        db.execSQL(sql);
    }

    if (oldVersion <= 17 && newVersion >= 18) {
        //create search table
        this.createSearchTable(db);

        // alter quiz results table
        String sql1 = "ALTER TABLE " + QUIZATTEMPTS_TABLE + " ADD COLUMN " + QUIZATTEMPTS_C_USERID
                + " integer default 0;";
        db.execSQL(sql1);

        // alter tracker table
        String sql2 = "ALTER TABLE " + TRACKER_LOG_TABLE + " ADD COLUMN " + TRACKER_LOG_C_USERID
                + " integer default 0;";
        db.execSQL(sql2);

        // create user table
        this.createUserTable(db);

    }

    if (oldVersion <= 18 && newVersion >= 19) {

        // alter quiz results table
        String sql1 = "ALTER TABLE " + QUIZATTEMPTS_TABLE + " ADD COLUMN " + QUIZATTEMPTS_C_SCORE
                + " real default 0;";
        db.execSQL(sql1);
        String sql2 = "ALTER TABLE " + QUIZATTEMPTS_TABLE + " ADD COLUMN " + QUIZATTEMPTS_C_PASSED
                + " integer default 0;";
        db.execSQL(sql2);

        // alter user table
        String sql3 = "ALTER TABLE " + USER_TABLE + " ADD COLUMN " + USER_C_LAST_LOGIN_DATE + " datetime null;";
        db.execSQL(sql3);
        String sql4 = "ALTER TABLE " + USER_TABLE + " ADD COLUMN " + USER_C_NO_LOGINS + " integer default 0;";
        db.execSQL(sql4);
        //create client table
        db.execSQL("DROP TABLE IF EXISTS " + CLIENT_TABLE);
        this.createClientTable(db);
    }

    if (oldVersion <= 19 && newVersion >= 20) {

        db.execSQL("DROP TABLE IF EXISTS " + CLIENT_TRACKER_TABLE);
        this.createClientTrackerTable(db);

        String sql = "ALTER TABLE " + CLIENT_TABLE + " ADD COLUMN " + CLIENT_C_AGEYOUNGESTCHILD
                + " integer default 0;";
        try {
            db.execSQL(sql);
        } catch (Exception e) {
        }
        sql = "ALTER TABLE " + CLIENT_TABLE + " ADD COLUMN " + CLIENT_C_HUSBANDNAME + " text null ;";
        try {
            db.execSQL(sql);
        } catch (Exception e) {
        }
        sql = "ALTER TABLE " + CLIENT_TABLE + " ADD COLUMN " + CLIENT_C_METHODNAME + " text null ;";
        try {
            db.execSQL(sql);
        } catch (Exception e) {
        }
        sql = "ALTER TABLE " + CLIENT_TABLE + " ADD COLUMN " + CLIENT_CLOSE_CASE + " integer default 0;";
        try {
            db.execSQL(sql);
        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
        }
        sql = "ALTER TABLE " + CLIENT_TABLE + " ADD COLUMN " + CLIENT_DELETE_RECORD + " integer default 0;";
        try {
            db.execSQL(sql);
        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
        }
        sql = "ALTER TABLE " + CLIENT_TABLE + " ADD COLUMN " + CLIENT_ADAPTED_METHOD_NAME + " TEXT null;";
        try {
            db.execSQL(sql);
        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
        }
        sql = "ALTER TABLE " + CLIENT_TABLE + " ADD COLUMN " + CLIENT_ADAPTED_METHOD_TIME + " integer;";
        try {
            db.execSQL(sql);
        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
        }
        sql = "ALTER TABLE " + CLIENT_TABLE + " ADD COLUMN " + CLIENT_LAST_CREATED + " integer default 0;";
        try {
            db.execSQL(sql);
        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
        }
        // alter quiz results table
        String sql1 = "ALTER TABLE " + QUIZATTEMPTS_TABLE + " ADD COLUMN " + QUIZATTEMPTS_C_MAXSCORE
                + " real default 0;";
        db.execSQL(sql1);
    }

    if (oldVersion <= 20 && newVersion >= 21) {
        db.execSQL("DROP TABLE IF EXISTS " + CLIENT_TABLE);
        this.createClientTable(db);
        // alter quiz results table
        String sql1 = "ALTER TABLE " + QUIZATTEMPTS_TABLE + " ADD COLUMN " + QUIZATTEMPTS_C_ACTIVITY_DIGEST
                + " text;";
        db.execSQL(sql1);
    }

    if (oldVersion <= 21 && newVersion >= 22) {
        // add points and badges columns
        String sql1 = "ALTER TABLE " + USER_TABLE + " ADD COLUMN " + USER_C_POINTS + " integer default 0;";
        db.execSQL(sql1);
        String sql2 = "ALTER TABLE " + USER_TABLE + " ADD COLUMN " + USER_C_BADGES + " integer default 0;";
        db.execSQL(sql2);

    }
    if (oldVersion <= 22 && newVersion >= 23) {
        // update courses
        db.execSQL("drop table if exists " + COURSE_TABLE);
        db.execSQL("drop table if exists " + ACTIVITY_TABLE);
        db.execSQL("drop table if exists " + TRACKER_LOG_TABLE);
        db.execSQL("drop table if exists " + QUIZATTEMPTS_TABLE);
        createCourseTable(db);
        createActivityTable(db);
        createLogTable(db);
        createQuizAttemptsTable(db);
    }
}

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  o  m*/
        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;
        }
    }
}

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 {/*from  w w  w  . ja va  2  s  .  co  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;
        }
    }
}