Example usage for android.database.sqlite SQLiteDatabase endTransaction

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

Introduction

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

Prototype

public void endTransaction() 

Source Link

Document

End a transaction.

Usage

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

/**
 * Deletes the server conflict row (if any) for this rowId in this tableId.
 * /*w ww  . ja va  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:com.cyanogenmod.eleven.provider.LocalizedStore.java

/**
 * This will grab all the songs from the medistore and add the localized data to the db
 * @param selection if we only want to do this for some songs, this selection will filter it out
 */// w w  w  . j a  v a 2  s.com
private void updateLocalizedStore(final SQLiteDatabase db, final String selection) {
    db.beginTransaction();
    try {
        Cursor cursor = null;

        try {
            final String combinedSelection = MusicUtils.MUSIC_ONLY_SELECTION
                    + (TextUtils.isEmpty(selection) ? "" : " AND " + selection);

            // order by artist/album/id to minimize artist/album re-inserts
            final String orderBy = AudioColumns.ARTIST_ID + "," + AudioColumns.ALBUM + "," + AudioColumns._ID;

            if (DEBUG) {
                Log.d(TAG, "Running selection query: " + combinedSelection);
            }

            cursor = mContext.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    new String[] {
                            // 0
                            AudioColumns._ID,
                            // 1
                            AudioColumns.TITLE,
                            // 2
                            AudioColumns.ARTIST_ID,
                            // 3
                            AudioColumns.ARTIST,
                            // 4
                            AudioColumns.ALBUM_ID,
                            // 5
                            AudioColumns.ALBUM, },
                    combinedSelection, null, orderBy);

            long previousArtistId = -1;
            long previousAlbumId = -1;
            long artistId;
            long albumId;

            if (cursor != null && cursor.moveToFirst()) {
                do {
                    albumId = cursor.getLong(4);
                    artistId = cursor.getLong(2);

                    if (artistId != previousArtistId) {
                        previousArtistId = artistId;
                        updateArtistData(db, artistId, cursor.getString(3));
                    }

                    if (albumId != previousAlbumId) {
                        previousAlbumId = albumId;

                        updateAlbumData(db, albumId, cursor.getString(5), artistId);
                    }

                    updateSongData(db, cursor.getLong(0), cursor.getString(1), artistId, albumId);
                } while (cursor.moveToNext());
            }
        } finally {
            if (cursor != null) {
                cursor.close();
                cursor = null;
            }
        }

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

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

/**
 * Update the schema and data-modification ETags of a given tableId.
 * //from w w w  .jav a  2  s .c o m
 * @param db
 * @param tableId
 * @param schemaETag
 * @param lastDataETag
 */
public void updateDBTableETags(SQLiteDatabase db, String tableId, String schemaETag, String lastDataETag) {
    if (tableId == null || tableId.length() <= 0) {
        throw new IllegalArgumentException(t + ": application name and table name must be specified");
    }

    ContentValues cvTableDef = new ContentValues();
    cvTableDef.put(TableDefinitionsColumns.SCHEMA_ETAG, schemaETag);
    cvTableDef.put(TableDefinitionsColumns.LAST_DATA_ETAG, lastDataETag);

    boolean dbWithinTransaction = db.inTransaction();
    try {
        if (!dbWithinTransaction) {
            db.beginTransaction();
        }
        db.update(DatabaseConstants.TABLE_DEFS_TABLE_NAME, cvTableDef, TableDefinitionsColumns.TABLE_ID + "=?",
                new String[] { tableId });
        if (!dbWithinTransaction) {
            db.setTransactionSuccessful();
        }
    } finally {
        if (!dbWithinTransaction) {
            db.endTransaction();
        }
    }
}

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 ava2 s  . c  om
 * @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:net.smart_json_database.JSONDatabase.java

public int update(JSONEntity entity) {
    int returnValue = -1;
    if (entity.getUid() == -1) {
        return returnValue;
    }//from www . j a va  2s .c  o m

    SQLiteDatabase db = dbHelper.getWritableDatabase();

    try {
        db.beginTransaction();
        entity.setUpdateDate(new Date());
        ContentValues values = new ContentValues();
        values.put("data", entity.getData().toString());
        values.put("updateDate", Util.DateToString(entity.getUpdateDate()));
        values.put("type", entity.getType());
        String[] params = new String[] { "" + entity.getUid() };
        db.update(TABLE_JSON_DATA, values, "json_uid = ?", params);
        for (String name : entity.getTags().getToAdd()) {
            int tagid = -1;
            if (!tags.containsKey(name)) {
                tagid = insertTag(name, db);
            } else {
                tagid = tags.get(name);
            }
            if (relateTagWithJsonEntity(tagid, entity.getUid(), db) == -1) {
                throw new Exception("could not relate");
            }

        }
        for (String name : entity.getTags().getToRemove()) {
            int tagid = -1;
            if (!tags.containsKey(name)) {
                continue;
            } else {
                tagid = tags.get(name);
            }

            db.delete(TABLE_REL_TAG_JSON_DATA, "to_id = ?", new String[] { "" + tagid });
        }

        for (HasMany hasMany : entity.getHasManyRelations().values()) {
            for (Integer id : hasMany.getToRemove()) {
                deleteRelation(hasMany.getName(), entity.getUid(), id, db);
            }

            for (Integer id : hasMany.getToAdd()) {
                insertRelation(hasMany.getName(), entity.getUid(), id, db);
            }
        }

        for (BelongsTo belongsTo : entity.getBelongsToRelations().values()) {
            for (Integer id : belongsTo.getToRemove()) {
                deleteRelation(belongsTo.getName(), id, entity.getUid(), db);
            }

            for (Integer id : belongsTo.getToAdd()) {
                insertRelation(belongsTo.getName(), id, entity.getUid(), db);
            }
        }

        db.setTransactionSuccessful();
        returnValue = entity.getUid();
        notifyListenersOnEntityChange(returnValue, IDatabaseChangeListener.CHANGETYPE_UPDATE);
    } catch (Exception e) {
        returnValue = -1;
    } finally {
        db.endTransaction();
        db.close();
    }
    return returnValue;

}

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

    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:com.zetaDevelopment.phonegap.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Executes a batch request and sends the results via sendJavascriptCB().
 *
 * @param dbname//from ww  w.  j  a va2 s  . c  o m
 *            The name of the database.
 *
 * @param queryarr
 *            Array of query strings
 *
 * @param jsonparams
 *            Array of JSON query parameters
 *
 * @param queryIDs
 *            Array of query ids
 *
 * @param tx_id
 *            Transaction id
 *
 */
private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonparams, String[] queryIDs,
        String tx_id) {
    SQLiteDatabase mydb = this.getDatabase(dbname);

    if (mydb == null)
        return;

    try {
        mydb.beginTransaction();

        String query = "";
        String query_id = "";
        int len = queryarr.length;

        for (int i = 0; i < len; i++) {
            query = queryarr[i];
            query_id = queryIDs[i];
            if (query.toLowerCase(Locale.getDefault()).startsWith("insert") && jsonparams != null) {
                SQLiteStatement myStatement = mydb.compileStatement(query);
                for (int j = 0; j < jsonparams[i].length(); j++) {
                    if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double) {
                        myStatement.bindDouble(j + 1, jsonparams[i].getDouble(j));
                    } else if (jsonparams[i].get(j) instanceof Number) {
                        myStatement.bindLong(j + 1, jsonparams[i].getLong(j));
                    } else {
                        myStatement.bindString(j + 1, jsonparams[i].getString(j));
                    }
                }
                long insertId = myStatement.executeInsert();

                String result = "{'insertId':'" + insertId + "'}";
                this.sendJavascriptCB("window.SQLitePluginTransactionCB.queryCompleteCallback('" + tx_id + "','"
                        + query_id + "', " + result + ");");
            } else {
                String[] params = null;

                if (jsonparams != null) {
                    params = new String[jsonparams[i].length()];

                    for (int j = 0; j < jsonparams[i].length(); j++) {
                        if (jsonparams[i].isNull(j))
                            params[j] = "";
                        else
                            params[j] = jsonparams[i].getString(j);
                    }
                }

                Cursor myCursor = mydb.rawQuery(query, params);

                if (query_id.length() > 0)
                    this.processResults(myCursor, query_id, tx_id);

                myCursor.close();
            }
        }
        mydb.setTransactionSuccessful();
    } catch (SQLiteException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } catch (JSONException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } finally {
        mydb.endTransaction();
        Log.v("executeSqlBatch", tx_id);
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txCompleteCallback('" + tx_id + "');");
    }
}

From source file:eu.inmite.apps.smsjizdenka.service.UpdateService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent == null) {
        return;/*from  w ww.j  ava  2s. c o  m*/
    }
    final boolean force = intent.getBooleanExtra("force", false);
    try {
        Locale loc = Locale.getDefault();
        String lang = loc.getISO3Language(); // http://www.loc.gov/standards/iso639-2/php/code_list.php; T-values if present both T and B
        if (lang == null || lang.length() == 0) {
            lang = "";
        }

        int serverVersion = intent.getIntExtra("serverVersion", -1);
        boolean fromPush = serverVersion != -1;
        JSONObject versionJson = null;
        if (!fromPush) {
            versionJson = getVersion(true);
            serverVersion = versionJson.getInt("version");
        }
        int localVersion = Preferences.getInt(c, Preferences.DATA_VERSION, -1);
        final String localLanguage = Preferences.getString(c, Preferences.DATA_LANGUAGE, "");

        if (serverVersion <= localVersion && !force && lang.equals(localLanguage)
                && !LOCAL_DEFINITION_TESTING) {
            // don't update
            DebugLog.i("Nothing new, not updating");
            return;
        }

        // update but don't notify about it.
        boolean firstLaunchNoUpdate = ((localVersion == -1
                && getVersion(false).getInt("version") == serverVersion) || !lang.equals(localLanguage));

        if (!firstLaunchNoUpdate) {
            DebugLog.i("There are new definitions available!");
        }

        handleAuthorMessage(versionJson, lang, intent, fromPush);

        InputStream is = getIS(URL_TICKETS_ID);
        try {
            String json = readResult(is);

            JSONObject o = new JSONObject(json);
            JSONArray array = o.getJSONArray("tickets");

            final SQLiteDatabase db = DatabaseHelper.get(this).getWritableDatabase();
            for (int i = 0; i < array.length(); i++) {
                final JSONObject city = array.getJSONObject(i);
                try {

                    final ContentValues cv = new ContentValues();
                    cv.put(Cities._ID, city.getInt("id"));
                    cv.put(Cities.CITY, getStringLocValue(city, lang, "city"));
                    if (city.has("city_pubtran")) {
                        cv.put(Cities.CITY_PUBTRAN, city.getString("city_pubtran"));
                    }
                    cv.put(Cities.COUNTRY, city.getString("country"));
                    cv.put(Cities.CURRENCY, city.getString("currency"));
                    cv.put(Cities.DATE_FORMAT, city.getString("dateFormat"));
                    cv.put(Cities.IDENTIFICATION, city.getString("identification"));
                    cv.put(Cities.LAT, city.getDouble("lat"));
                    cv.put(Cities.LON, city.getDouble("lon"));
                    cv.put(Cities.NOTE, getStringLocValue(city, lang, "note"));
                    cv.put(Cities.NUMBER, city.getString("number"));
                    cv.put(Cities.P_DATE_FROM, city.getString("pDateFrom"));
                    cv.put(Cities.P_DATE_TO, city.getString("pDateTo"));
                    cv.put(Cities.P_HASH, city.getString("pHash"));
                    cv.put(Cities.PRICE, city.getString("price"));
                    cv.put(Cities.PRICE_NOTE, getStringLocValue(city, lang, "priceNote"));
                    cv.put(Cities.REQUEST, city.getString("request"));
                    cv.put(Cities.VALIDITY, city.getInt("validity"));
                    if (city.has("confirmReq")) {
                        cv.put(Cities.CONFIRM_REQ, city.getString("confirmReq"));
                    }
                    if (city.has("confirm")) {
                        cv.put(Cities.CONFIRM, city.getString("confirm"));
                    }

                    final JSONArray additionalNumbers = city.getJSONArray("additionalNumbers");
                    for (int j = 0; j < additionalNumbers.length() && j < 3; j++) {
                        cv.put("ADDITIONAL_NUMBER_" + (j + 1), additionalNumbers.getString(j));
                    }

                    db.beginTransaction();
                    int count = db.update(DatabaseHelper.CITY_TABLE_NAME, cv,
                            Cities._ID + " = " + cv.getAsInteger(Cities._ID), null);
                    if (count == 0) {
                        db.insert(DatabaseHelper.CITY_TABLE_NAME, null, cv);
                    }

                    db.setTransactionSuccessful();
                    getContentResolver().notifyChange(Cities.CONTENT_URI, null);
                } finally {
                    if (db.inTransaction()) {
                        db.endTransaction();
                    }
                }
            }
            Preferences.set(c, Preferences.DATA_VERSION, serverVersion);
            Preferences.set(c, Preferences.DATA_LANGUAGE, lang);
            if (!firstLaunchNoUpdate && !fromPush) {
                final int finalServerVersion = serverVersion;
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(UpdateService.this,
                                getString(R.string.cities_update_completed, finalServerVersion),
                                Toast.LENGTH_LONG).show();
                    }
                });
            }
            if (LOCAL_DEFINITION_TESTING) {
                DebugLog.w(
                        "Local definition testing - data updated from assets - must be removed in production!");
            }
        } finally {
            is.close();
        }
    } catch (IOException e) {
        DebugLog.e("IOException when calling update: " + e.getMessage(), e);
    } catch (JSONException e) {
        DebugLog.e("JSONException when calling update: " + e.getMessage(), e);
    }
}

From source file:com.digicorp.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Executes a batch request and sends the results via sendJavascriptCB().
 *
 * @param dbname/*w  w w .  ja  v a 2 s  .co m*/
 *            The name of the database.
 *
 * @param queryarr
 *            Array of query strings
 *
 * @param jsonparams
 *            Array of JSON query parameters
 *
 * @param queryIDs
 *            Array of query ids
 *
 * @param tx_id
 *            Transaction id
 *
 */
private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonparams, String[] queryIDs,
        String tx_id) {
    SQLiteDatabase mydb = this.getDatabase(dbname);

    if (mydb == null)
        return;

    try {
        mydb.beginTransaction();

        String query = "";
        String query_id = "";
        int len = queryarr.length;

        for (int i = 0; i < len; i++) {
            query = queryarr[i];
            query_id = queryIDs[i];
            if (query.toLowerCase().startsWith("insert") && jsonparams != null) {
                SQLiteStatement myStatement = mydb.compileStatement(query);
                for (int j = 0; j < jsonparams[i].length(); j++) {
                    if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double) {
                        myStatement.bindDouble(j + 1, jsonparams[i].getDouble(j));
                    } else if (jsonparams[i].get(j) instanceof Number) {
                        myStatement.bindLong(j + 1, jsonparams[i].getLong(j));
                    } else if (jsonparams[i].isNull(j)) {
                        myStatement.bindNull(j + 1);
                    } else {
                        myStatement.bindString(j + 1, jsonparams[i].getString(j));
                    }
                }
                long insertId = myStatement.executeInsert();

                String result = "{'insertId':'" + insertId + "'}";
                this.sendJavascriptCB("window.SQLitePluginTransactionCB.queryCompleteCallback('" + tx_id + "','"
                        + query_id + "', " + result + ");");
            } else {
                String[] params = null;

                if (jsonparams != null) {
                    params = new String[jsonparams[i].length()];

                    for (int j = 0; j < jsonparams[i].length(); j++) {
                        if (jsonparams[i].isNull(j))
                            params[j] = "";
                        else
                            params[j] = jsonparams[i].getString(j);
                    }
                }

                Cursor myCursor = mydb.rawQuery(query, params);

                if (query_id.length() > 0)
                    this.processResults(myCursor, query_id, tx_id);

                myCursor.close();
            }
        }
        mydb.setTransactionSuccessful();
    } catch (SQLiteException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } catch (JSONException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } finally {
        mydb.endTransaction();
        Log.v("executeSqlBatch", tx_id);
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txCompleteCallback('" + tx_id + "');");
    }
}