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.provider.impl.FormsProviderImpl.java

/**
 * This method removes the entry from the content provider, and also removes
 * any associated files. files: form.xml, [formmd5].formdef, formname
 * {directory}//from   w w  w . j a v a 2  s .  c om
 */
@Override
public int delete(Uri uri, 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);
    }

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

    Cursor del = null;
    Integer idValue = null;
    String tableIdValue = null;
    String formIdValue = null;
    HashMap<File, DirType> mediaDirs = new HashMap<File, DirType>();
    try {
        del = this.query(uri, null, whereId, whereIdArgs, null);
        if (del == null) {
            throw new SQLException("FAILED Delete into " + uri + " -- unable to query for existing records");
        }
        del.moveToPosition(-1);
        while (del.moveToNext()) {
            idValue = ODKDatabaseUtils.get().getIndexAsType(del, Integer.class,
                    del.getColumnIndex(FormsColumns._ID));
            tableIdValue = ODKDatabaseUtils.get().getIndexAsString(del,
                    del.getColumnIndex(FormsColumns.TABLE_ID));
            formIdValue = ODKDatabaseUtils.get().getIndexAsString(del,
                    del.getColumnIndex(FormsColumns.FORM_ID));
            File mediaDir = ODKFileUtils.asAppFile(appName, ODKDatabaseUtils.get().getIndexAsString(del,
                    del.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)));
            mediaDirs.put(mediaDir, (tableIdValue == null) ? DirType.FRAMEWORK : DirType.FORMS);
        }
    } catch (Exception e) {
        log.w(t, "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString());

        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else {
            throw new SQLException(
                    "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString());
        }
    } finally {
        if (del != null && !del.isClosed()) {
            del.close();
        }
    }

    SQLiteDatabase db = null;
    int count;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();
        count = db.delete(DatabaseConstants.FORMS_TABLE_NAME, whereId, whereIdArgs);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        e.printStackTrace();
        log.w(t, "Unable to perform deletion " + e.toString());
        return 0;
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }

    // and attempt to move these directories to the stale forms location
    // so that they do not immediately get rescanned...

    for (HashMap.Entry<File, DirType> entry : mediaDirs.entrySet()) {
        try {
            moveDirectory(appName, entry.getValue(), entry.getKey());
        } catch (IOException e) {
            e.printStackTrace();
            log.e(t, "Unable to move directory " + e.toString());
        }
    }

    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.example.android.touroflondon.data.TourDbHelper.java

/**
 * Extract Route data from a {@link JSONArray} of save it in the database.
 *
 * @param data//from w  ww  . j a v a  2  s  .c o  m
 */
public void loadRoute(JSONArray data) throws JSONException {

    SQLiteDatabase db = this.getWritableDatabase();

    // Empty the route table to remove all existing data
    db.delete(TourContract.RouteEntry.TABLE_NAME, null, null);

    // Need to complete transaction first to clear data
    db.close();

    // Begin the insert transaction
    db = this.getWritableDatabase();
    db.beginTransaction();

    // Loop over each location in array
    for (int i = 0; i < data.length(); i++) {
        // extract data
        JSONObject poi = data.getJSONObject(i);
        final double lat = poi.getDouble("lat");
        final double lng = poi.getDouble("lng");

        // Construct insert statement
        ContentValues cv = new ContentValues();
        cv.put(TourContract.RouteEntry.COLUMN_NAME_LAT, lat);
        cv.put(TourContract.RouteEntry.COLUMN_NAME_LNG, lng);

        // Insert data
        db.insert(TourContract.RouteEntry.TABLE_NAME, null, cv);
    }

    if (db != null) {
        // All insert statement have been submitted, mark transaction as successful
        db.setTransactionSuccessful();
        db.endTransaction();
    }
}

From source file:com.example.google.touroflondon.data.TourDbHelper.java

/**
 * Extract Route data from a {@link JSONArray} of save it in the database.
 * //w  w w.  j  a v  a2 s .c  o  m
 * @param data
 */
public void loadRoute(JSONArray data) throws JSONException {

    SQLiteDatabase db = this.getWritableDatabase();

    // Empty the route table to remove all existing data
    db.delete(TourContract.RouteEntry.TABLE_NAME, null, null);

    // Need to complete transaction first to clear data
    db.close();

    // Begin the insert transaction
    db = this.getWritableDatabase();
    db.beginTransaction();

    // Loop over each location in array
    for (int i = 0; i < data.length(); i++) {
        // extract data
        JSONObject poi = data.getJSONObject(i);
        final double lat = poi.getDouble("lat");
        final double lng = poi.getDouble("lng");

        // Construct insert statement
        ContentValues cv = new ContentValues();
        cv.put(TourContract.RouteEntry.COLUMN_NAME_LAT, lat);
        cv.put(TourContract.RouteEntry.COLUMN_NAME_LNG, lng);

        // Insert data
        db.insert(TourContract.RouteEntry.TABLE_NAME, null, cv);
    }

    if (db != null) {
        // All insert statement have been submitted, mark transaction as
        // successful
        db.setTransactionSuccessful();
        db.endTransaction();
    }
}

From source file:org.devtcg.five.provider.FiveSyncAdapter.java

@Override
public void getServerDiffs(SyncContext context, AbstractSyncProvider serverDiffs) {
    if (mSource != ((FiveProvider) serverDiffs).mSource)
        throw new IllegalStateException("What the hell happened here?");

    context.moreRecordsToGet = true;//from   w ww  .j  a v a 2 s  .  co  m

    /* Source must have been deleted or something? */
    if (mSource.moveToFirst() == false)
        return;

    AuthHelper.setCredentials(sClient, mSource);

    long modifiedSince;

    SQLiteDatabase db = serverDiffs.getDatabase();
    db.beginTransaction();
    try {
        modifiedSince = getServerDiffsImpl(context, serverDiffs, FEED_ARTISTS);
        if (modifiedSince >= 0)
            getImageData(context, serverDiffs, FEED_ARTISTS, modifiedSince);

        modifiedSince = getServerDiffsImpl(context, serverDiffs, FEED_ALBUMS);
        if (modifiedSince >= 0)
            getImageData(context, serverDiffs, FEED_ALBUMS, modifiedSince);

        getServerDiffsImpl(context, serverDiffs, FEED_SONGS);
        getServerDiffsImpl(context, serverDiffs, FEED_PLAYLISTS);
        getServerDiffsImpl(context, serverDiffs, FEED_PLAYLIST_SONGS);

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

    /* This is a very naive implementation... */
    if (context.hasCanceled() == false && context.hasError() == false)
        context.moreRecordsToGet = false;
}

From source file:net.smart_json_database.JSONDatabase.java

public boolean deleteAll() {
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    boolean returnValue = false;
    try {//from   ww w .j a va 2s .c om
        db.beginTransaction();
        db.delete(TABLE_REL_JSON_DATA_JSON_DATA, "", null);
        db.delete(TABLE_REL_JSON_DATA_JSON_DATA, "", null);
        db.delete(TABLE_REL_TAG_JSON_DATA, "", null);
        db.delete(TABLE_JSON_DATA, "", null);
        db.setTransactionSuccessful();
        returnValue = true;
    } catch (Exception e) {
        returnValue = false;
    } finally {
        db.endTransaction();
        db.close();
    }
    return returnValue;
}

From source file:edu.asu.bscs.csiebler.waypointdatabase.MainActivity.java

private JSONArray getJsonResults() {
    JSONArray resultSet = new JSONArray();

    try {//from  w  ww.j ava 2 s  . c  om
        WaypointDB db = new WaypointDB(this);
        db.copyDB();
        SQLiteDatabase waypointDB = db.openDB();
        waypointDB.beginTransaction();

        String searchQuery = "SELECT  * FROM waypoint";
        Cursor cursor = waypointDB.rawQuery(searchQuery, null);

        cursor.moveToFirst();

        while (cursor.isAfterLast() == false) {
            int totalColumn = cursor.getColumnCount();
            JSONObject rowObject = new JSONObject();

            for (int i = 0; i < totalColumn; i++) {
                if (cursor.getColumnName(i) != null) {
                    try {
                        if (cursor.getString(i) != null) {
                            Log.d("TAG_NAME", cursor.getString(i));
                            rowObject.put(cursor.getColumnName(i), cursor.getString(i));
                        } else {
                            rowObject.put(cursor.getColumnName(i), "");
                        }
                    } catch (Exception e) {
                        Log.d("TAG_NAME", e.getMessage());
                    }
                }
            }

            resultSet.put(rowObject);
            cursor.moveToNext();
        }

        cursor.close();
        waypointDB.endTransaction();
        waypointDB.close();
        db.close();

        Log.d("TAG_NAME", resultSet.toString());
    } catch (Exception ex) {
        Log.w(getClass().getSimpleName(), "Exception creating adapter: " + ex.getMessage());
    }

    return resultSet;
}

From source file:ru.orangesoftware.financisto2.db.MyEntityManager.java

public long insertBudget(Budget budget) {
    SQLiteDatabase db = db();
    db.beginTransaction();// ww w  .  j a va  2  s  .  c  o m
    try {
        if (budget.id > 0) {
            deleteBudget(budget.id);
        }
        long id = 0;
        Recur recur = RecurUtils.createFromExtraString(budget.recur);
        Period[] periods = RecurUtils.periods(recur);
        for (int i = 0; i < periods.length; i++) {
            Period p = periods[i];
            budget.id = -1;
            budget.parentBudgetId = id;
            budget.recurNum = i;
            budget.startDate = p.start;
            budget.endDate = p.end;
            long bid = super.saveOrUpdate(budget);
            if (i == 0) {
                id = bid;
            }
        }
        db.setTransactionSuccessful();
        return id;
    } finally {
        db.endTransaction();
    }
}

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);
    }//w w w .j  a  v  a2  s.co 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();//from  w ww  .ja  va2s  .  c o m
    try {
        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:com.cyanogenmod.eleven.provider.LocalizedStore.java

private void rebuildLocaleData(LocaleSet locales) {
    if (DEBUG) {//from w ww  .java 2  s .  c o  m
        Log.d(TAG, "Locale has changed, rebuilding sorting data");
    }

    final long start = SystemClock.elapsedRealtime();
    final SQLiteDatabase db = mMusicDatabase.getWritableDatabase();
    db.beginTransaction();
    try {
        db.execSQL("DELETE FROM " + SongSortColumns.TABLE_NAME);
        db.execSQL("DELETE FROM " + AlbumSortColumns.TABLE_NAME);
        db.execSQL("DELETE FROM " + ArtistSortColumns.TABLE_NAME);

        // prep the localization classes
        mLocaleSetManager.updateLocaleSet(locales);

        updateLocalizedStore(db, null);

        // Update the ICU version used to generate the locale derived data
        // so we can tell when we need to rebuild with new ICU versions.
        PropertiesStore.getInstance(mContext).storeProperty(PropertiesStore.DbProperties.ICU_VERSION,
                ICU.getIcuVersion());
        PropertiesStore.getInstance(mContext).storeProperty(PropertiesStore.DbProperties.LOCALE,
                locales.toString());

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

    if (DEBUG) {
        Log.i(TAG, "Locale change completed in " + (SystemClock.elapsedRealtime() - start) + "ms");
    }
}