Example usage for android.database.sqlite SQLiteDatabase setTransactionSuccessful

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

Introduction

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

Prototype

public void setTransactionSuccessful() 

Source Link

Document

Marks the current transaction as successful.

Usage

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

@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() != 3) {
        throw new SQLException("Unknown URI (does not specify instance!) " + uri);
    }// ww w .  j  a v a2 s . c o m

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);

    String tableId = segments.get(1);
    // _ID in UPLOADS_TABLE_NAME
    String instanceId = segments.get(2);

    SQLiteDatabase db = null;
    int count = 0;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);

        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 + "\"";

        // run the query to get all the ids...
        List<IdStruct> idStructs = new ArrayList<IdStruct>();
        Cursor ref = null;
        try {
            // use this provider's query interface to get the set of ids that
            // match (if any)
            ref = this.query(uri, null, where, whereArgs, null);
            if (ref.getCount() != 0) {
                ref.moveToFirst();
                do {
                    String iId = ODKDatabaseUtils.get().getIndexAsString(ref,
                            ref.getColumnIndex(InstanceColumns._ID));
                    String iIdDataTable = ODKDatabaseUtils.get().getIndexAsString(ref,
                            ref.getColumnIndex(InstanceColumns.DATA_INSTANCE_ID));
                    idStructs.add(new IdStruct(iId, iIdDataTable));
                } while (ref.moveToNext());
            }
        } finally {
            if (ref != null) {
                ref.close();
            }
        }

        // update the values string...
        if (values.containsKey(InstanceColumns.XML_PUBLISH_STATUS)) {
            Date xmlPublishDate = new Date();
            values.put(InstanceColumns.XML_PUBLISH_TIMESTAMP,
                    TableConstants.nanoSecondsFromMillis(xmlPublishDate.getTime()));
            String xmlPublishStatus = values.getAsString(InstanceColumns.XML_PUBLISH_STATUS);
            if (values.containsKey(InstanceColumns.DISPLAY_SUBTEXT) == false) {
                String text = getDisplaySubtext(xmlPublishStatus, xmlPublishDate);
                values.put(InstanceColumns.DISPLAY_SUBTEXT, text);
            }
        }

        db.beginTransaction();
        String[] args = new String[1];
        for (IdStruct idStruct : idStructs) {
            args[0] = idStruct.idUploadsTable;
            count += db.update(DatabaseConstants.UPLOADS_TABLE_NAME, values, InstanceColumns._ID + "=?", args);
        }
        db.setTransactionSuccessful();
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return count;
}

From source file:org.opendatakit.sync.ProcessRowDataChanges.java

private UserTable updateLocalRowsFromServerChanges(TableResource tableResource, TableDefinitionEntry te,
        ArrayList<ColumnDefinition> orderedColumns, String displayName, boolean deferInstanceAttachments,
        ArrayList<ColumnDefinition> fileAttachmentColumns, List<SyncRowPending> rowsToPushFileAttachments,
        UserTable localDataTable, RowResourceList rows) throws IOException {

    String tableId = tableResource.getTableId();
    TableResult tableResult = sc.getTableResult(tableId);

    if (rows.getRows().isEmpty()) {
        // nothing here -- let caller determine whether we are done or
        // whether we need to issue another request to the server.
        return localDataTable;
    }//from www  .  ja  v a2 s . com

    Map<String, SyncRow> changedServerRows = new HashMap<String, SyncRow>();
    for (RowResource row : rows.getRows()) {
        SyncRow syncRow = new SyncRow(row.getRowId(), row.getRowETag(), row.isDeleted(), row.getFormId(),
                row.getLocale(), row.getSavepointType(), row.getSavepointTimestamp(), row.getSavepointCreator(),
                row.getFilterScope(), row.getValues(), fileAttachmentColumns);
        changedServerRows.put(row.getRowId(), syncRow);
    }

    sc.updateNotification(SyncProgressState.ROWS, R.string.anaylzing_row_changes, new Object[] { tableId }, 7.0,
            false);

    /**************************
     * PART 2: UPDATE THE DATA
     **************************/
    log.d(TAG, "updateDbFromServer setServerHadDataChanges(true)");
    tableResult.setServerHadDataChanges(!changedServerRows.isEmpty());
    // these are all the various actions we will need to take:

    // serverRow updated; no matching localRow
    List<SyncRowDataChanges> rowsToInsertLocally = new ArrayList<SyncRowDataChanges>();

    // serverRow updated; localRow SyncState is synced or
    // synced_pending_files
    List<SyncRowDataChanges> rowsToUpdateLocally = new ArrayList<SyncRowDataChanges>();

    // serverRow deleted; localRow SyncState is synced or
    // synced_pending_files
    List<SyncRowDataChanges> rowsToDeleteLocally = new ArrayList<SyncRowDataChanges>();

    // serverRow updated or deleted; localRow SyncState is not synced or
    // synced_pending_files
    List<SyncRowDataChanges> rowsToMoveToInConflictLocally = new ArrayList<SyncRowDataChanges>();

    // loop through the localRow table
    for (int i = 0; i < localDataTable.getNumberOfRows(); i++) {
        Row localRow = localDataTable.getRowAtIndex(i);
        String stateStr = localRow.getRawDataOrMetadataByElementKey(DataTableColumns.SYNC_STATE);
        SyncState state = stateStr == null ? null : SyncState.valueOf(stateStr);

        String rowId = localRow.getRowId();

        // see if there is a change to this row from our current
        // server change set.
        SyncRow serverRow = changedServerRows.get(rowId);

        if (serverRow == null) {
            continue;
        }

        // OK -- the server is reporting a change (in serverRow) to the
        // localRow.
        // if the localRow is already in a in_conflict state, determine
        // what its
        // ConflictType is. If the localRow holds the earlier server-side
        // change,
        // then skip and look at the next record.
        int localRowConflictTypeBeforeSync = -1;
        if (state == SyncState.in_conflict) {
            // we need to remove the in_conflict records that refer to the
            // prior state of the server
            String localRowConflictTypeBeforeSyncStr = localRow
                    .getRawDataOrMetadataByElementKey(DataTableColumns.CONFLICT_TYPE);
            localRowConflictTypeBeforeSync = localRowConflictTypeBeforeSyncStr == null ? null
                    : Integer.parseInt(localRowConflictTypeBeforeSyncStr);
            if (localRowConflictTypeBeforeSync == ConflictType.SERVER_DELETED_OLD_VALUES
                    || localRowConflictTypeBeforeSync == ConflictType.SERVER_UPDATED_UPDATED_VALUES) {
                // This localRow holds the server values from a
                // previously-identified conflict.
                // Skip it -- we will clean up this copy later once we find
                // the matching localRow
                // that holds the locally-changed values that were in conflict
                // with this earlier
                // set of server values.
                continue;
            }
        }

        // remove this server row from the map of changes reported by the
        // server.
        // the following decision tree will always place the row into one
        // of the
        // local action lists.
        changedServerRows.remove(rowId);

        // OK the record is either a simple local record or a local
        // in_conflict record
        if (state == SyncState.synced || state == SyncState.synced_pending_files) {
            // the server's change should be applied locally.
            //
            // the file attachments might be stale locally,
            // but those are dealt with separately.

            if (serverRow.isDeleted()) {
                rowsToDeleteLocally.add(new SyncRowDataChanges(serverRow,
                        SyncRow.convertToSyncRow(orderedColumns, fileAttachmentColumns, localRow),
                        (state == SyncState.synced_pending_files)));
            } else {
                rowsToUpdateLocally.add(new SyncRowDataChanges(serverRow,
                        SyncRow.convertToSyncRow(orderedColumns, fileAttachmentColumns, localRow),
                        (state == SyncState.synced_pending_files)));
            }
        } else if (serverRow.isDeleted() && (state == SyncState.deleted || (state == SyncState.in_conflict
                && localRowConflictTypeBeforeSync == ConflictType.LOCAL_DELETED_OLD_VALUES))) {
            // this occurs if
            // (1) a delete request was never ACKed but it was performed
            // on the server.
            // (2) if there is an unresolved conflict held locally with the
            // local action being to delete the record, and the prior server
            // state being a value change, but the newly sync'd state now
            // reflects a deletion by another party.
            //

            // no need to worry about server in_conflict records.
            // any server in_conflict rows will be deleted during the delete
            // step
            rowsToDeleteLocally.add(new SyncRowDataChanges(serverRow,
                    SyncRow.convertToSyncRow(orderedColumns, fileAttachmentColumns, localRow), false));
        } else {
            // SyncState.deleted and server is not deleting
            // SyncState.new_row and record exists on server
            // SyncState.changed and new change on server
            // SyncState.in_conflict and new change on server

            // no need to worry about server in_conflict records.
            // any server in_conflict rows will be cleaned up during the
            // update of the in_conflict state.

            // figure out what the localRow conflict type should be...
            Integer localRowConflictType;
            if (state == SyncState.changed) {
                // SyncState.changed and new change on server
                localRowConflictType = ConflictType.LOCAL_UPDATED_UPDATED_VALUES;
                log.i(TAG, "local row was in sync state CHANGED, changing to "
                        + "IN_CONFLICT and setting conflict type to: " + localRowConflictType);
            } else if (state == SyncState.new_row) {
                // SyncState.new_row and record exists on server
                // The 'new_row' case occurs if an insert is never ACKed but
                // completes successfully on the server.
                localRowConflictType = ConflictType.LOCAL_UPDATED_UPDATED_VALUES;
                log.i(TAG, "local row was in sync state NEW_ROW, changing to "
                        + "IN_CONFLICT and setting conflict type to: " + localRowConflictType);
            } else if (state == SyncState.deleted) {
                // SyncState.deleted and server is not deleting
                localRowConflictType = ConflictType.LOCAL_DELETED_OLD_VALUES;
                log.i(TAG, "local row was in sync state DELETED, changing to "
                        + "IN_CONFLICT and updating conflict type to: " + localRowConflictType);
            } else if (state == SyncState.in_conflict) {
                // SyncState.in_conflict and new change on server
                // leave the local conflict type unchanged (retrieve it and
                // use it).
                localRowConflictType = localRowConflictTypeBeforeSync;
                log.i(TAG,
                        "local row was in sync state IN_CONFLICT, leaving as "
                                + "IN_CONFLICT and leaving conflict type unchanged as: "
                                + localRowConflictTypeBeforeSync);
            } else {
                throw new IllegalStateException("Unexpected state encountered");
            }
            SyncRowDataChanges syncRow = new SyncRowDataChanges(serverRow,
                    SyncRow.convertToSyncRow(orderedColumns, fileAttachmentColumns, localRow), false,
                    localRowConflictType);

            if (!syncRow.identicalValues(orderedColumns)) {
                if (syncRow.identicalValuesExceptRowETagAndFilterScope(orderedColumns)) {
                    // just apply the server RowETag and filterScope to the
                    // local row
                    rowsToUpdateLocally.add(new SyncRowDataChanges(serverRow,
                            SyncRow.convertToSyncRow(orderedColumns, fileAttachmentColumns, localRow), true));
                } else {
                    rowsToMoveToInConflictLocally.add(syncRow);
                }
            } else {
                log.w(TAG, "identical rows returned from server -- SHOULDN'T THESE NOT HAPPEN?");
            }
        }
    }

    // Now, go through the remaining serverRows in the rows map. That
    // map now contains only row changes that don't affect any existing
    // localRow. If the server change is not a row-deletion / revoke-row
    // action, then insert the serverRow locally.
    for (SyncRow serverRow : changedServerRows.values()) {
        boolean isDeleted = serverRow.isDeleted();
        if (!isDeleted) {
            rowsToInsertLocally.add(new SyncRowDataChanges(serverRow, null, false));
        }
    }

    //
    // OK we have captured the local inserting, locally updating,
    // locally deleting and conflicting actions. And we know
    // the changes for the server. Determine the per-row percentage
    // for applying all these changes

    int totalChange = rowsToInsertLocally.size() + rowsToUpdateLocally.size() + rowsToDeleteLocally.size()
            + rowsToMoveToInConflictLocally.size();

    perRowIncrement = 70.0 / ((double) (totalChange + 1));
    rowsProcessed = 0;
    boolean hasAttachments = !fileAttachmentColumns.isEmpty();

    // i.e., we have created entries in the various action lists
    // for all the actions we should take.

    // ///////////////////////////////////////////////////
    // / PERFORM LOCAL DATABASE CHANGES
    // / PERFORM LOCAL DATABASE CHANGES
    // / PERFORM LOCAL DATABASE CHANGES
    // / PERFORM LOCAL DATABASE CHANGES
    // / PERFORM LOCAL DATABASE CHANGES

    {
        SQLiteDatabase db = null;
        try {
            db = sc.getDatabase();

            // this will individually move some files to the locally-deleted state
            // if we cannot sync file attachments in those rows.
            pushLocalAttachmentsBeforeDeleteRowsInDb(db, tableResource, rowsToDeleteLocally,
                    fileAttachmentColumns, deferInstanceAttachments, tableResult);

            // and now do a big transaction to update the local database.
            db.beginTransaction();

            deleteRowsInDb(db, tableResource, rowsToDeleteLocally, fileAttachmentColumns,
                    deferInstanceAttachments, tableResult);

            insertRowsInDb(db, tableResource, orderedColumns, rowsToInsertLocally, rowsToPushFileAttachments,
                    hasAttachments, tableResult);

            updateRowsInDb(db, tableResource, orderedColumns, rowsToUpdateLocally, rowsToPushFileAttachments,
                    hasAttachments, tableResult);

            conflictRowsInDb(db, tableResource, orderedColumns, rowsToMoveToInConflictLocally,
                    rowsToPushFileAttachments, hasAttachments, tableResult);

            localDataTable = ODKDatabaseUtils.get().rawSqlQuery(db, sc.getAppName(), tableId, orderedColumns,
                    null, null, null, null, DataTableColumns.ID, "ASC");

            // TODO: fix this for synced_pending_files
            // We likely need to relax this constraint on the
            // server?

            db.setTransactionSuccessful();
        } finally {
            if (db != null) {
                db.endTransaction();
                db.close();
                db = null;
            }
        }
    }

    return localDataTable;
}

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

/**
 * Update the ETag and SyncState of a given rowId. There should be exactly one
 * record for this rowId in thed database (i.e., no conflicts or checkpoints).
 * // w w  w.j  ava2  s. c  o m
 * @param db
 * @param tableId
 * @param rowId
 * @param rowETag
 * @param state
 */
public void updateRowETagAndSyncState(SQLiteDatabase db, String tableId, String rowId, String rowETag,
        SyncState state) {

    String whereClause = DataTableColumns.ID + " = ?";
    String[] whereArgs = { rowId };

    ContentValues cvDataTableVal = new ContentValues();

    String sel = "SELECT * FROM " + tableId + " WHERE " + whereClause;
    String[] selArgs = whereArgs;
    Cursor cursor = rawQuery(db, sel, selArgs);

    // There must be only one row in the db
    if (cursor.getCount() != 1) {
        throw new IllegalArgumentException(
                t + ": row id " + rowId + " does not have exactly 1 row in table " + tableId);
    }

    cvDataTableVal.put(DataTableColumns.ROW_ETAG, rowETag);
    cvDataTableVal.put(DataTableColumns.SYNC_STATE, state.name());

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

        db.update(tableId, cvDataTableVal, whereClause, whereArgs);

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

}

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  av  a  2s  .c  om
 */
@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.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 ww . j  a  va  2  s  . c om*/
        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;
        }
    }
}

From source file:com.newsrob.EntryManager.java

private void deleteArticlesFromDb(final SyncJob job, final List<String> articleIdsToDeleteInDatabase) {
    if (articleIdsToDeleteInDatabase.isEmpty())
        return;/*from w  w w . java2 s.c  o  m*/

    Timing t2 = new Timing("Delete Articles From Db", ctx);

    job.setJobDescription("Cleaning up database");
    job.target = articleIdsToDeleteInDatabase.size();
    job.actual = 0;
    fireStatusUpdated();

    SQLiteDatabase db = databaseHelper.getDb();

    final String sql1 = "DELETE FROM " + Entries.TABLE_NAME + " WHERE " + Entries.__ID + "=?;";
    final String sql2 = "DELETE FROM " + EntryLabelAssociations.TABLE_NAME + " WHERE "
            + EntryLabelAssociations.ENTRY_ID + "=?;";

    final SQLiteStatement stmt1 = db.compileStatement(sql1);
    final SQLiteStatement stmt2 = db.compileStatement(sql2);

    try {

        // outter loop does the chunking and holds the transaction context
        while (!articleIdsToDeleteInDatabase.isEmpty()) {

            db.beginTransaction();

            while (!articleIdsToDeleteInDatabase.isEmpty()) {

                String id = articleIdsToDeleteInDatabase.remove(0);
                stmt1.bindString(1, id);
                stmt1.execute();
                stmt2.bindString(1, id);
                stmt2.execute();

                job.actual++;

                if (job.actual % 10 == 0)
                    fireStatusUpdated();

                // commit every 35 articles
                if (job.actual >= 35)
                    break;
            }

            db.setTransactionSuccessful();
            db.endTransaction();
        }
    } finally {
        stmt1.close();
        stmt2.close();
    }
    fireStatusUpdated();
    t2.stop();
}

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);/*  w  ww  . j av a 2s . c  o  m*/
        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

/**
 * The deletion filter includes all non-null arguments. If all arguments
 * (except the db) are null, then all properties are removed.
 * /*from   ww w.j a v  a 2s  .  c  o 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:ru.orangesoftware.financisto2.db.DatabaseAdapter.java

private long duplicateTransaction(long id, int isTemplate, int multiplier) {
    SQLiteDatabase db = db();
    db.beginTransaction();/* w  w  w .  j  a va 2  s .  c  o  m*/
    try {
        long now = System.currentTimeMillis();
        Transaction transaction = getTransaction(id);
        if (transaction.isSplitChild()) {
            id = transaction.parentId;
            transaction = getTransaction(id);
        }
        transaction.lastRecurrence = now;
        updateTransaction(transaction);
        transaction.id = -1;
        transaction.isTemplate = isTemplate;
        transaction.dateTime = now;
        transaction.remoteKey = null;
        if (isTemplate == 0) {
            transaction.recurrence = null;
            transaction.notificationOptions = null;
        }
        if (multiplier > 1) {
            transaction.fromAmount *= multiplier;
            transaction.toAmount *= multiplier;
        }
        long transactionId = insertTransaction(transaction);
        Map<Long, String> attributesMap = getAllAttributesForTransaction(id);
        LinkedList<TransactionAttribute> attributes = new LinkedList<TransactionAttribute>();
        for (long attributeId : attributesMap.keySet()) {
            TransactionAttribute ta = new TransactionAttribute();
            ta.attributeId = attributeId;
            ta.value = attributesMap.get(attributeId);
            attributes.add(ta);
        }
        if (attributes.size() > 0) {
            insertAttributes(transactionId, attributes);
        }
        List<Transaction> splits = getSplitsForTransaction(id);
        if (multiplier > 1) {
            for (Transaction split : splits) {
                split.fromAmount *= multiplier;
                split.remoteKey = null;
            }
        }
        transaction.id = transactionId;
        transaction.splits = splits;
        insertSplits(transaction);
        db.setTransactionSuccessful();
        return transactionId;
    } finally {
        db.endTransaction();
    }
}

From source file:com.google.android.apps.santatracker.service.APIProcessor.java

private int processRoute(JSONArray json) {
    SQLiteDatabase db = mDestinationDBHelper.getWritableDatabase();

    db.beginTransaction();//from w  w  w .j a v a2s . com
    try {
        // loop over each destination
        long previousPresents = mPreferences.getTotalPresents();

        int i;
        for (i = 0; i < json.length(); i++) {
            JSONObject dest = json.getJSONObject(i);

            JSONObject location = dest.getJSONObject(FIELD_DETAILS_LOCATION);

            long presentsTotal = dest.getLong(FIELD_DETAILS_PRESENTSDELIVERED);
            long presents = presentsTotal - previousPresents;
            previousPresents = presentsTotal;

            // Name
            String city = dest.getString(FIELD_DETAILS_CITY);
            String region = null;
            String country = null;

            if (dest.has(FIELD_DETAILS_REGION)) {
                region = dest.getString(FIELD_DETAILS_REGION);
                if (region.length() < 1) {
                    region = null;
                }
            }
            if (dest.has(FIELD_DETAILS_COUNTRY)) {
                country = dest.getString(FIELD_DETAILS_COUNTRY);
                if (country.length() < 1) {
                    country = null;
                }
            }

            //                if (mDebugLog) {
            //                    Log.d(TAG, "Location: " + city);
            //                }

            // Detail fields
            JSONObject details = dest.getJSONObject(FIELD_DETAILS_DETAILS);
            long timezone = details.isNull(FIELD_DETAILS_TIMEZONE) ? 0L
                    : details.getLong(FIELD_DETAILS_TIMEZONE);
            long altitude = details.getLong(FIELD_DETAILS_ALTITUDE);
            String photos = details.has(FIELD_DETAILS_PHOTOS) ? details.getString(FIELD_DETAILS_PHOTOS)
                    : EMPTY_STRING;
            String weather = details.has(FIELD_DETAILS_WEATHER) ? details.getString(FIELD_DETAILS_WEATHER)
                    : EMPTY_STRING;
            String streetview = details.has(FIELD_DETAILS_STREETVIEW)
                    ? details.getString(FIELD_DETAILS_STREETVIEW)
                    : EMPTY_STRING;
            String gmmStreetview = details.has(FIELD_DETAILS_GMMSTREETVIEW)
                    ? details.getString(FIELD_DETAILS_GMMSTREETVIEW)
                    : EMPTY_STRING;

            try {
                // All parsed, insert into DB
                mDestinationDBHelper.insertDestination(db, dest.getString(FIELD_IDENTIFIER),
                        dest.getLong(FIELD_ARRIVAL), dest.getLong(FIELD_DEPARTURE),

                        city, region, country,

                        location.getDouble(FIELD_DETAILS_LOCATION_LAT),
                        location.getDouble(FIELD_DETAILS_LOCATION_LNG), presentsTotal, presents, timezone,
                        altitude, photos, weather, streetview, gmmStreetview);
            } catch (android.database.sqlite.SQLiteConstraintException e) {
                // ignore duplicate locations
            }
        }

        db.setTransactionSuccessful();
        // Update mPreferences
        mPreferences.setDBTimestamp(System.currentTimeMillis());
        mPreferences.setTotalPresents(previousPresents);
        return i;
    } catch (JSONException e) {
        Log.d(TAG, "Santa location tracking error 30");
        SantaLog.d(TAG, "JSON Exception", e);
    } finally {
        db.endTransaction();
    }

    return 0;
}