Example usage for android.database.sqlite SQLiteDatabase beginTransaction

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

Introduction

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

Prototype

public void beginTransaction() 

Source Link

Document

Begins a transaction in EXCLUSIVE mode.

Usage

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

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() < 2 || segments.size() > 3) {
        throw new SQLException("Unknown URI (too many segments!) " + uri);
    }//www  . jav  a  2  s  . c  o  m

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

    SQLiteDatabase db = null;
    String fullQuery;
    String filterArgs[];
    Cursor c = null;

    String dbTableName;
    List<ColumnDefinition> orderedDefns;

    StringBuilder b = new StringBuilder();

    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);
        }

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

        try {
            c = db.query(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME,
                    new String[] { KeyValueStoreColumns.VALUE },
                    KeyValueStoreColumns.TABLE_ID + "=? AND " + KeyValueStoreColumns.PARTITION + "=? AND "
                            + KeyValueStoreColumns.ASPECT + "=? AND " + KeyValueStoreColumns.KEY + "=?",
                    new String[] { tableId, KeyValueStoreConstants.PARTITION_TABLE,
                            KeyValueStoreConstants.ASPECT_DEFAULT, KeyValueStoreConstants.XML_INSTANCE_NAME },
                    null, null, null);

            if (c.getCount() == 1) {
                c.moveToFirst();
                int idxInstanceName = c.getColumnIndex(KeyValueStoreColumns.VALUE);
                instanceName = c.getString(idxInstanceName);
            }
        } finally {
            c.close();
        }

        // ARGH! we must ensure that we have records in our UPLOADS_TABLE_NAME
        // for every distinct instance in the data table.
        b.setLength(0);
        //@formatter:off
        b.append("INSERT INTO ").append(DatabaseConstants.UPLOADS_TABLE_NAME).append("(")
                .append(InstanceColumns.DATA_INSTANCE_ID).append(",")
                .append(InstanceColumns.DATA_TABLE_TABLE_ID).append(") ").append("SELECT ")
                .append(InstanceColumns.DATA_INSTANCE_ID).append(",")
                .append(InstanceColumns.DATA_TABLE_TABLE_ID).append(" FROM (").append("SELECT DISTINCT ")
                .append(DATA_TABLE_ID_COLUMN).append(" as ").append(InstanceColumns.DATA_INSTANCE_ID)
                .append(",").append("? as ").append(InstanceColumns.DATA_TABLE_TABLE_ID).append(" FROM ")
                .append(dbTableName).append(" EXCEPT SELECT DISTINCT ").append(InstanceColumns.DATA_INSTANCE_ID)
                .append(",").append(InstanceColumns.DATA_TABLE_TABLE_ID).append(" FROM ")
                .append(DatabaseConstants.UPLOADS_TABLE_NAME).append(")");
        //@formatter:on

        // TODO: should we collapse across FORM_ID or leave it this way?
        String[] args = { tableId };
        db.execSQL(b.toString(), args);

        // Can't get away with dataTable.* because of collision with _ID column
        // get map of (elementKey -> ColumnDefinition)
        try {
            orderedDefns = TableUtil.get().getColumnDefinitions(db, appName, tableId);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            throw new SQLException("Unable to retrieve column definitions for tableId " + tableId);
        }

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

    ////////////////////////////////////////////////////////////////
    // OK we have the info we need -- now build the query we want...

    // We can now join through and access the data table rows

    b.setLength(0);
    // @formatter:off
    b.append("SELECT ");
    b.append(DatabaseConstants.UPLOADS_TABLE_NAME).append(".").append(InstanceColumns._ID).append(" as ")
            .append(InstanceColumns._ID).append(",").append(DatabaseConstants.UPLOADS_TABLE_NAME).append(".")
            .append(InstanceColumns.DATA_INSTANCE_ID).append(" as ").append(InstanceColumns.DATA_INSTANCE_ID)
            .append(",").append(DatabaseConstants.UPLOADS_TABLE_NAME).append(".")
            .append(InstanceColumns.SUBMISSION_INSTANCE_ID).append(" as ")
            .append(InstanceColumns.SUBMISSION_INSTANCE_ID).append(",");
    // add the dataTable metadata except for _ID (which conflicts with InstanceColumns._ID)
    b.append(dbTableName).append(".").append(DataTableColumns.ROW_ETAG).append(" as ")
            .append(DataTableColumns.ROW_ETAG).append(",").append(dbTableName).append(".")
            .append(DataTableColumns.SYNC_STATE).append(" as ").append(DataTableColumns.SYNC_STATE).append(",")
            .append(dbTableName).append(".").append(DataTableColumns.CONFLICT_TYPE).append(" as ")
            .append(DataTableColumns.CONFLICT_TYPE).append(",").append(dbTableName).append(".")
            .append(DataTableColumns.FILTER_TYPE).append(" as ").append(DataTableColumns.FILTER_TYPE)
            .append(",").append(dbTableName).append(".").append(DataTableColumns.FILTER_VALUE).append(" as ")
            .append(DataTableColumns.FILTER_VALUE).append(",").append(dbTableName).append(".")
            .append(DataTableColumns.FORM_ID).append(" as ").append(DataTableColumns.FORM_ID).append(",")
            .append(dbTableName).append(".").append(DataTableColumns.LOCALE).append(" as ")
            .append(DataTableColumns.LOCALE).append(",").append(dbTableName).append(".")
            .append(DataTableColumns.SAVEPOINT_TYPE).append(" as ").append(DataTableColumns.SAVEPOINT_TYPE)
            .append(",").append(dbTableName).append(".").append(DataTableColumns.SAVEPOINT_TIMESTAMP)
            .append(" as ").append(DataTableColumns.SAVEPOINT_TIMESTAMP).append(",").append(dbTableName)
            .append(".").append(DataTableColumns.SAVEPOINT_CREATOR).append(" as ")
            .append(DataTableColumns.SAVEPOINT_CREATOR).append(",");
    // add the user-specified data fields in this dataTable
    for (ColumnDefinition cd : orderedDefns) {
        if (cd.isUnitOfRetention()) {
            b.append(dbTableName).append(".").append(cd.getElementKey()).append(" as ")
                    .append(cd.getElementKey()).append(",");
        }
    }
    b.append("CASE WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" IS NULL THEN null")
            .append(" WHEN ").append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" IS NULL THEN null")
            .append(" WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" > ")
            .append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" THEN null").append(" ELSE ")
            .append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" END as ")
            .append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(",");
    b.append("CASE WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" IS NULL THEN null")
            .append(" WHEN ").append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" IS NULL THEN null")
            .append(" WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" > ")
            .append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" THEN null").append(" ELSE ")
            .append(InstanceColumns.XML_PUBLISH_STATUS).append(" END as ")
            .append(InstanceColumns.XML_PUBLISH_STATUS).append(",");
    b.append("CASE WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" IS NULL THEN null")
            .append(" WHEN ").append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" IS NULL THEN null")
            .append(" WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" > ")
            .append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" THEN null").append(" ELSE ")
            .append(InstanceColumns.DISPLAY_SUBTEXT).append(" END as ").append(InstanceColumns.DISPLAY_SUBTEXT)
            .append(",");
    if (instanceName == null) {
        b.append(DataTableColumns.SAVEPOINT_TIMESTAMP);
    } else {
        b.append(instanceName);
    }
    b.append(" as ").append(InstanceColumns.DISPLAY_NAME);
    b.append(" FROM ");
    b.append("( SELECT * FROM ").append(dbTableName).append(" AS T WHERE T.")
            .append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append("=(SELECT MAX(V.")
            .append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(") FROM ").append(dbTableName)
            .append(" AS V WHERE V.").append(DATA_TABLE_ID_COLUMN).append("=T.").append(DATA_TABLE_ID_COLUMN)
            .append(" AND V.").append(DATA_TABLE_SAVEPOINT_TYPE_COLUMN).append(" IS NOT NULL").append(")")
            .append(") as ").append(dbTableName);
    b.append(" JOIN ").append(DatabaseConstants.UPLOADS_TABLE_NAME).append(" ON ").append(dbTableName)
            .append(".").append(DATA_TABLE_ID_COLUMN).append("=").append(DatabaseConstants.UPLOADS_TABLE_NAME)
            .append(".").append(InstanceColumns.DATA_INSTANCE_ID).append(" AND ").append("? =")
            .append(DatabaseConstants.UPLOADS_TABLE_NAME).append(".")
            .append(InstanceColumns.DATA_TABLE_TABLE_ID);
    b.append(" WHERE ").append(DATA_TABLE_SAVEPOINT_TYPE_COLUMN).append("=?");
    // @formatter:on

    if (instanceId != null) {
        b.append(" AND ").append(DatabaseConstants.UPLOADS_TABLE_NAME).append(".").append(InstanceColumns._ID)
                .append("=?");
        String tempArgs[] = { tableId, InstanceColumns.STATUS_COMPLETE, instanceId };
        filterArgs = tempArgs;
    } else {
        String tempArgs[] = { tableId, InstanceColumns.STATUS_COMPLETE };
        filterArgs = tempArgs;
    }

    if (selection != null) {
        b.append(" AND (").append(selection).append(")");
    }

    if (selectionArgs != null) {
        String[] tempArgs = new String[filterArgs.length + selectionArgs.length];
        for (int i = 0; i < filterArgs.length; ++i) {
            tempArgs[i] = filterArgs[i];
        }
        for (int i = 0; i < selectionArgs.length; ++i) {
            tempArgs[filterArgs.length + i] = selectionArgs[i];
        }
        filterArgs = tempArgs;
    }

    if (sortOrder != null) {
        b.append(" ORDER BY ").append(sortOrder);
    }

    fullQuery = b.toString();

    db = null;
    boolean success = false;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        c = db.rawQuery(fullQuery, filterArgs);
        // Tell the cursor what uri to watch, so it knows when its source data
        // changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        success = true;
        return c;
    } finally {
        if (db != null && !success) {
            // leave database open for cursor...
            db.close();
        }
    }
}

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

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

    if (segments.size() < 1 || segments.size() > 2) {
        throw new IllegalArgumentException("Unknown URI (incorrect number of segments!) " + uri);
    }/*from w  w w.j a  v  a  2  s .  c  o  m*/

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

    String uriFormId = ((segments.size() == 2) ? segments.get(1) : null);
    boolean isNumericId = StringUtils.isNumeric(uriFormId);

    // Modify the where clause to account for the presence of
    // a form id. Accept either:
    // (1) numeric _ID value
    // (2) string FORM_ID value.
    String whereId;
    String[] whereIdArgs;

    if (uriFormId == null) {
        whereId = where;
        whereIdArgs = whereArgs;
    } else {
        if (TextUtils.isEmpty(where)) {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=?";
            whereIdArgs = new String[1];
            whereIdArgs[0] = uriFormId;
        } else {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=? AND (" + where + ")";
            whereIdArgs = new String[whereArgs.length + 1];
            whereIdArgs[0] = uriFormId;
            for (int i = 0; i < whereArgs.length; ++i) {
                whereIdArgs[i + 1] = whereArgs[i];
            }
        }
    }

    /*
     * First, find out what records match this query, and if they refer to two
     * or more (formId,formVersion) tuples, then be sure to remove all
     * FORM_MEDIA_PATH references. Otherwise, if they are all for the same
     * tuple, and the update specifies a FORM_MEDIA_PATH, move all the
     * non-matching directories elsewhere.
     */
    Integer idValue = null;
    String tableIdValue = null;
    String formIdValue = null;
    HashMap<File, DirType> mediaDirs = new HashMap<File, DirType>();
    boolean multiset = false;
    Cursor c = null;
    try {
        c = this.query(uri, null, whereId, whereIdArgs, null);
        if (c == null) {
            throw new SQLException(
                    "FAILED Update of " + uri + " -- query for existing row did not return a cursor");
        }
        if (c.getCount() >= 1) {
            FormIdVersion ref = null;
            c.moveToPosition(-1);
            while (c.moveToNext()) {
                idValue = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class,
                        c.getColumnIndex(FormsColumns._ID));
                tableIdValue = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.TABLE_ID));
                formIdValue = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.FORM_ID));
                String tableId = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.TABLE_ID));
                String formId = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.FORM_ID));
                String formVersion = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.FORM_VERSION));
                FormIdVersion cur = new FormIdVersion(tableId, formId, formVersion);

                int appRelativeMediaPathIdx = c.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH);
                String mediaPath = ODKDatabaseUtils.get().getIndexAsString(c, appRelativeMediaPathIdx);
                if (mediaPath != null) {
                    mediaDirs.put(ODKFileUtils.asAppFile(appName, mediaPath),
                            (tableIdValue == null) ? DirType.FRAMEWORK : DirType.FORMS);
                }

                if (ref != null && !ref.equals(cur)) {
                    multiset = true;
                    break;
                } else {
                    ref = cur;
                }
            }
        }
    } catch (Exception e) {
        log.w(t, "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString());

        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else {
            throw new SQLException(
                    "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString());
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }

    if (multiset) {
        // don't let users manually update media path
        // we are referring to two or more (formId,formVersion) tuples.
        if (values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) {
            values.remove(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH);
        }
    } else if (values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) {
        // we are not a multiset and we are setting the media path
        // try to move all the existing non-matching media paths to
        // somewhere else...
        File mediaPath = ODKFileUtils.asAppFile(appName,
                values.getAsString(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH));
        for (HashMap.Entry<File, DirType> entry : mediaDirs.entrySet()) {
            File altPath = entry.getKey();
            if (!altPath.equals(mediaPath)) {
                try {
                    moveDirectory(appName, entry.getValue(), altPath);
                } catch (IOException e) {
                    e.printStackTrace();
                    log.e(t, "Attempt to move " + altPath.getAbsolutePath() + " failed: " + e.toString());
                }
            }
        }
        // OK. we have moved the existing form definitions elsewhere. We can
        // proceed with update...
    }

    // ensure that all values are correct and ignore some user-supplied
    // values...
    patchUpValues(appName, values);

    // Make sure that the necessary fields are all set
    if (values.containsKey(FormsColumns.DATE) == true) {
        Date today = new Date();
        String ts = new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time),
                Locale.getDefault()).format(today);
        values.put(FormsColumns.DISPLAY_SUBTEXT, ts);
    }

    SQLiteDatabase db = null;
    int count;
    try {
        // OK Finally, now do the update...
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();
        count = db.update(DatabaseConstants.FORMS_TABLE_NAME, values, whereId, whereIdArgs);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        e.printStackTrace();
        log.w(t, "Unable to perform update " + uri);
        return 0;
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }

    if (count == 1) {
        Uri formUri = Uri.withAppendedPath(
                Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), formIdValue);
        getContext().getContentResolver().notifyChange(formUri, null);
        Uri idUri = Uri.withAppendedPath(
                Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                Long.toString(idValue));
        getContext().getContentResolver().notifyChange(idUri, null);
    } else {
        getContext().getContentResolver().notifyChange(uri, null);
    }
    return count;
}

From source file:com.appsimobile.appsii.module.home.provider.HomeContentProvider.java

@Override
public int bulkInsert(Uri uri, @NonNull ContentValues[] values) {
    SqlArguments args = new SqlArguments(uri);

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    db.beginTransaction();
    try {/*from  w  w w .  j  a  v a2 s .  c  om*/
        int numValues = values.length;
        for (int i = 0; i < numValues; i++) {
            ContentValues value = values[i];
            if (db.insert(args.table, null, value) < 0)
                return 0;
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }

    sendNotify(uri);
    return values.length;
}

From source file:it.bradipao.berengar.DbTool.java

public static int gson2db(SQLiteDatabase mDB, File jsonFile) {

    // vars/*  w w w.  j  a  va2s  .  c  om*/
    int iTableNum = 0;
    FileReader fr = null;
    BufferedReader br = null;
    JsonReader jr = null;
    String name = null;
    String val = null;

    String mTable = null;
    String mTableSql = null;
    ArrayList<String> aFields = null;
    ArrayList<String> aValues = null;
    ContentValues cv = null;

    // file readers
    try {
        fr = new FileReader(jsonFile);
        br = new BufferedReader(fr);
        jr = new JsonReader(br);
    } catch (FileNotFoundException e) {
        Log.e(LOGTAG, "error in gson2db file readers", e);
    }

    // parsing
    try {
        // start database transaction
        mDB.beginTransaction();
        // open root {
        jr.beginObject();
        // iterate through root objects
        while (jr.hasNext()) {
            name = jr.nextName();
            if (jr.peek() == JsonToken.NULL)
                jr.skipValue();
            // number of tables
            else if (name.equals("tables_num")) {
                val = jr.nextString();
                iTableNum = Integer.parseInt(val);
                if (GOLOG)
                    Log.d(LOGTAG, "TABLE NUM : " + iTableNum);
            }
            // iterate through tables array
            else if (name.equals("tables")) {
                jr.beginArray();
                while (jr.hasNext()) {
                    // start table
                    mTable = null;
                    aFields = null;
                    jr.beginObject();
                    while (jr.hasNext()) {
                        name = jr.nextName();
                        if (jr.peek() == JsonToken.NULL)
                            jr.skipValue();
                        // table name
                        else if (name.equals("table_name")) {
                            mTable = jr.nextString();
                        }
                        // table sql
                        else if (name.equals("table_sql")) {
                            mTableSql = jr.nextString();
                            if ((mTable != null) && (mTableSql != null)) {
                                mDB.execSQL("DROP TABLE IF EXISTS " + mTable);
                                mDB.execSQL(mTableSql);
                                if (GOLOG)
                                    Log.d(LOGTAG, "DROPPED AND CREATED TABLE : " + mTable);
                            }
                        }
                        // iterate through columns name
                        else if (name.equals("cols_name")) {
                            jr.beginArray();
                            while (jr.hasNext()) {
                                val = jr.nextString();
                                if (aFields == null)
                                    aFields = new ArrayList<String>();
                                aFields.add(val);
                            }
                            jr.endArray();
                            if (GOLOG)
                                Log.d(LOGTAG, "COLUMN NAME : " + aFields.toString());
                        }
                        // iterate through rows
                        else if (name.equals("rows")) {
                            jr.beginArray();
                            while (jr.hasNext()) {
                                jr.beginArray();
                                // iterate through values in row
                                aValues = null;
                                cv = null;
                                while (jr.hasNext()) {
                                    val = jr.nextString();
                                    if (aValues == null)
                                        aValues = new ArrayList<String>();
                                    aValues.add(val);
                                }
                                jr.endArray();
                                // add to database
                                cv = new ContentValues();
                                for (int j = 0; j < aFields.size(); j++)
                                    cv.put(aFields.get(j), aValues.get(j));
                                mDB.insert(mTable, null, cv);
                                if (GOLOG)
                                    Log.d(LOGTAG, "INSERT IN " + mTable + " : " + aValues.toString());
                            }
                            jr.endArray();
                        } else
                            jr.skipValue();
                    }
                    // end table
                    jr.endObject();
                }
                jr.endArray();
            } else
                jr.skipValue();
        }
        // close root }
        jr.endObject();
        jr.close();
        // successfull transaction
        mDB.setTransactionSuccessful();
    } catch (IOException e) {
        Log.e(LOGTAG, "error in gson2db gson parsing", e);
    } finally {
        mDB.endTransaction();
    }

    return iTableNum;
}

From source file:org.ohmage.db.DbHelper.java

/**
 * Used by the ContentProvider to insert a campaign and also insert into
 * interested tables. Don't use this directly; if you do, none of the
 * contentobservers, etc. that are listening to Campaigns, Surveys, or
 * SurveyPrompts will be notified.//from  w  w  w.  java2 s  .co m
 * 
 * @param values
 *            a ContentValues collection, preferably generated by calling
 *            {@link Campaign}'s toCV() method
 * @return the ID of the inserted record
 */
public long addCampaign(SQLiteDatabase db, ContentValues values) {

    long rowId = -1; // the row ID for the campaign that we'll eventually be
                     // returning

    try {
        // start the transaction that will include inserting the campaign +
        // surveys + survey prompts
        db.beginTransaction();

        // hold onto some variables for processing
        String configurationXml = values.getAsString(Campaigns.CAMPAIGN_CONFIGURATION_XML);
        String campaignUrn = values.getAsString(Campaigns.CAMPAIGN_URN);

        // actually insert the campaign
        rowId = db.insert(Tables.CAMPAIGNS, null, values);

        if (configurationXml != null) {
            // xml parsing below, inserts into Surveys and SurveyPrompts
            if (populateSurveysFromCampaignXML(db, campaignUrn, configurationXml)) {
                // i think we're done now; finish up the transaction
                db.setTransactionSuccessful();
            }
            // else we fail and the transaction gets rolled back
        } else {
            db.setTransactionSuccessful();
        }
    } finally {
        db.endTransaction();
    }

    return rowId;
}

From source file:org.path.episample.android.tasks.InitializationTask.java

private void registerCensusForm() {
    // create a census table in ODK Survey's database
    SQLiteDatabase db = null;

    try {/*w w w .j a v  a  2 s  .  c  o m*/
        // db = DatabaseFactory.getInstanceDatabase(context, appName);
        db = DatabaseFactory.get().getDatabase(getApplication(), getAppName());

        List<Column> columns = CensusColumns.USER_DEFINED_COLUMNS;

        ArrayList<ColumnDefinition> orderedDefs = ColumnDefinition.buildColumnDefinitions(appName,
                CensusDatabaseHelper.CENSUS_DATABASES_TABLE, columns);
        db.beginTransaction();
        ODKDatabaseUtils.get().createDBTableWithColumns(db, appName,
                CensusDatabaseHelper.CENSUS_DATABASES_TABLE, orderedDefs);
        db.setTransactionSuccessful();

        registerCensusFormInstanceName(db);

    } catch (Exception ex) {

    } finally {

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

From source file:org.ohmage.db.DbHelper.java

/**
 * Adds a response to the feedback database.
 * //from w w w  .j ava  2  s . c  om
 * @return the ID of the inserted record, or -1 if unsuccessful
 */
public long addResponseRow(SQLiteDatabase db, ContentValues values) {
    long rowId = -1;

    // extract data that we'll need to parse the json + insert prompt
    // responses
    String response = values.getAsString(Responses.RESPONSE_JSON);
    String campaignUrn = values.getAsString(Responses.CAMPAIGN_URN);
    String surveyId = values.getAsString(Responses.SURVEY_ID);

    try {
        // start a transaction involving the following operations:
        // 1) insert feedback response row
        // 2) parse json-encoded responses and insert one row into prompts
        // per entry
        db.beginTransaction();

        // do the actual insert into feedback responses
        rowId = db.insert(Tables.RESPONSES, null, values);

        // check if it succeeded; if not, we can't do anything
        if (rowId == -1)
            return -1;

        if (populatePromptsFromResponseJSON(db, rowId, response, campaignUrn, surveyId)) {
            // and we're done; finalize the transaction
            db.setTransactionSuccessful();
        }
        // else we fail and the transaction gets rolled back
    } catch (SQLiteConstraintException e) {
        Log.e(TAG, "Attempted to insert record that violated a SQL constraint (likely the hashcode)");
        return -1;
    } catch (Exception e) {
        Log.e(TAG, "Generic exception thrown from db insert", e);
        return -1;
    } finally {
        db.endTransaction();
        // db.close();
    }

    return rowId;
}

From source file:com.hichinaschool.flashcards.libanki.Collection.java

public synchronized void close(boolean save) {
    if (mDb != null) {
        if (!mConf.optBoolean("newBury", false)) {
            boolean mod = mDb.getMod();
            mSched.unburyCards();//from   w  w w  . ja  va 2 s.  c om
            mDb.setMod(mod);
        }
        try {
            SQLiteDatabase db = getDb().getDatabase();
            if (save) {
                db.beginTransaction();
                try {
                    save();
                    db.setTransactionSuccessful();
                } finally {
                    db.endTransaction();
                }
            } else {
                if (db.inTransaction()) {
                    db.endTransaction();
                }
                lock();
            }
        } catch (RuntimeException e) {
            AnkiDroidApp.saveExceptionReportFile(e, "closeDB");
        }
        AnkiDatabaseManager.closeDatabase(mPath);
        mDb = null;
        mMedia.close();
        // Log.i(AnkiDroidApp.TAG, "Collection closed");
    }
}

From source file:org.nuxeo.android.cache.sql.DeferedUpdateTableWrapper.java

public OperationRequest storeRequest(String key, OperationRequest request, OperationType opType) {

    SQLiteDatabase db = getWritableDatabase();

    String sql = "INSERT INTO " + getTableName() + " (" + KEY_COLUMN + "," + OPID_COLUMN + "," + OPTYPE_COLUMN
            + "," + PARAMS_COLUMN + "," + HEADERS_COLUMN + "," + CTX_COLUMN + "," + DEPS_COLUMN;

    String operationId = request.getDocumentation().getId();
    String jsonParams = new JSONObject(request.getParameters()).toString();
    String jsonHeaders = new JSONObject(request.getHeaders()).toString();
    String jsonCtx = new JSONObject(request.getContextParameters()).toString();
    String deps = request.getDependencies().asJSON();

    String sqlValues = " VALUES (" + "'" + key + "'," + "'" + operationId + "'," + "'" + opType.toString()
            + "'," + "'" + jsonParams + "'," + "'" + jsonHeaders + "'," + "'" + jsonCtx + "'," + "'" + deps
            + "'";

    if (request.getInput() != null) {
        String inputType = request.getInput().getInputType();
        String inputRef = request.getInput().getInputRef();
        String inputBin = new Boolean(request.getInput().isBinary()).toString();

        sql = sql + "," + INPUT_TYPE_COLUMN + "," + INPUT_REF_COLUMN + "," + INPUT_BINARY_COLUMN;
        sqlValues = sqlValues + ",'" + inputType + "','" + inputRef + "','" + inputBin + "'";
    }//from  ww  w .  j a  v  a 2s .c om
    String insertQuery = sql + " ) " + sqlValues + ");";
    db.beginTransaction();
    db.execSQL(insertQuery);
    db.setTransactionSuccessful();
    db.endTransaction();

    return request;
}

From source file:ru.gkpromtech.exhibition.db.DbHelper.java

public void applyUpdates(SQLiteDatabase db, JsonNode updates, boolean isStatic) throws Exception {

    JsonNode nodeRev = updates.get("revision");
    if (nodeRev == null)
        return;/*from w w  w  . j av a2 s  . c  om*/

    final String synchronous = getPragma(db, "synchronous");
    final String journalMode = getPragma(db, "journal_mode");

    db.rawQuery("PRAGMA synchronous = OFF", null);
    db.rawQuery("PRAGMA journal_mode = MEMORY", null);
    //  FK,  ?   ???    add-update
    db.execSQL("PRAGMA foreign_keys = OFF");

    SharedPreferences prefs = getPrefs();

    int langId = Profile.getInstance(mContext).getLangId();
    int currentRevision = prefs.getInt("revision", 0);
    ObjectMapper mapper = new ObjectMapper();
    int revision = nodeRev.asInt();
    ArrayNode nodeChanges = (ArrayNode) updates.get("changes");

    TypeReference<List<Change>> typeRef = new TypeReference<List<Change>>() {
    };
    List<Change> changes = mapper.readValue(nodeChanges.traverse(), typeRef);

    Map<Table, List<Integer>> deletedTableRowIds = new HashMap<>();

    try {
        db.beginTransaction();

        for (Change change : changes) {
            if (currentRevision > change.id) {
                Log.w("PPDB", "Skipping old change #" + change.id);
                continue;
            }

            boolean tr = change.entity.endsWith("_tr");
            String entityName = !tr ? change.entity : change.entity.substring(0, change.entity.length() - 3);

            Class<? extends Entity> entity = getEntityForTableName(entityName);
            if (entity == null) {
                Log.e("PPDB", "Cannot find entity for " + entityName);
                continue;
            }

            Table<? extends Entity> table = getTableFor(entity);
            if (table == null) {
                Log.e("PPDB", "Cannot find table for entity " + entityName);
                continue;
            }

            if (!tr) {
                if (change.data != null) {
                    switch (change.changetype) {
                    case Change.ADDED:
                        table.insert(db, change.data, SQLiteDatabase.CONFLICT_FAIL);
                        break;
                    case Change.UPDATED:
                        change.data.remove("id");
                        table.partialUpdate(db, change.rowid, change.data, SQLiteDatabase.CONFLICT_FAIL);
                        break;
                    }
                } else {
                    if (change.changetype == Change.DELETED) {
                        List<Integer> ids = deletedTableRowIds.get(table);
                        if (ids == null) {
                            ids = new ArrayList<>();
                            deletedTableRowIds.put(table, ids);
                        }
                        ids.add(change.rowid);
                    }
                }
            } else if (change.data != null) {
                int changeLangId = change.data.get("languageid").asInt();
                if (changeLangId != langId)
                    continue;
                change.data.remove("languageid");
                switch (change.changetype) {
                case Change.ADDED:
                case Change.UPDATED:
                    TableRef annotation = entity.getAnnotation(TableRef.class);
                    if (annotation == null) {
                        Log.e("PPDB", "Cannot get trid field for entity " + entityName);
                        continue;
                    }
                    String trIdName = annotation.trid();
                    JsonNode nodeTrId = change.data.get(trIdName);
                    if (nodeTrId == null) {
                        Log.e("PPDB", "Change data don't have a field [" + trIdName + "]: " + entityName);
                        continue;
                    }
                    int id = nodeTrId.asInt();
                    change.data.remove("id");
                    change.data.remove(trIdName);
                    table.partialUpdate(db, id, change.data, SQLiteDatabase.CONFLICT_FAIL);
                    break;
                }
            }
        }

        db.setTransactionSuccessful();

    } finally {
        db.endTransaction();
    }

    //   ??? ?, ? FK
    db.execSQL("PRAGMA foreign_keys = ON");

    try {
        db.beginTransaction();

        for (Map.Entry<Table, List<Integer>> entry : deletedTableRowIds.entrySet()) {
            Table table = entry.getKey();
            List<Integer> ids = entry.getValue();
            for (Integer id : ids)
                table.delete(db, id);
        }

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

    if (synchronous != null)
        db.rawQuery("PRAGMA synchronous = " + synchronous, null);
    if (journalMode != null)
        db.rawQuery("PRAGMA journal_mode = " + journalMode, null);

    if (revision > currentRevision)
        prefs.edit().putInt("revision", revision).apply();

    if (isStatic)
        prefs.edit().putInt("jsonRevision", revision).apply();
}