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

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

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

    ContentValues cvDataTableVal = new ContentValues();

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

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

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

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

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

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

}

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

@Override
public synchronized Uri insert(Uri uri, ContentValues initialValues) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() != 1) {
        throw new IllegalArgumentException("Unknown URI (too many segments!) " + uri);
    }// w ww. jav  a 2 s  . c o m

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

    ContentValues values;
    if (initialValues != null) {
        values = new ContentValues(initialValues);
    } else {
        values = new ContentValues();
    }

    // ODK2: require FORM_MEDIA_PATH (different behavior -- ODK1 and
    // required FORM_FILE_PATH)
    if (!values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) {
        throw new IllegalArgumentException(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + " must be specified.");
    }

    // Normalize path...
    File mediaPath = ODKFileUtils.asAppFile(appName,
            values.getAsString(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH));

    // require that the form directory actually exists
    if (!mediaPath.exists()) {
        throw new IllegalArgumentException(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH
                + " directory does not exist: " + mediaPath.getAbsolutePath());
    }

    patchUpValues(appName, values);

    if (values.containsKey(FormsColumns.DISPLAY_SUBTEXT) == false) {
        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);
    }

    if (values.containsKey(FormsColumns.DISPLAY_NAME) == false) {
        values.put(FormsColumns.DISPLAY_NAME, mediaPath.getName());
    }

    // first try to see if a record with this filename already exists...
    String[] projection = { FormsColumns.FORM_ID, FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH };
    String[] selectionArgs = { ODKFileUtils.asRelativePath(appName, mediaPath) };
    String selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "=?";
    Cursor c = null;

    SQLiteDatabase db = null;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();
        try {
            c = db.query(DatabaseConstants.FORMS_TABLE_NAME, projection, selection, selectionArgs, null, null,
                    null);
            if (c == null) {
                throw new SQLException("FAILED Insert into " + uri
                        + " -- unable to query for existing records: " + mediaPath.getAbsolutePath());
            }
            if (c.getCount() > 0) {
                // already exists
                throw new SQLException("FAILED Insert into " + uri
                        + " -- row already exists for form directory: " + mediaPath.getAbsolutePath());
            }
        } catch (Exception e) {
            log.w(t, "FAILED Insert into " + uri + " -- query for existing row failed: " + e.toString());

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

        try {
            long rowId = db.insert(DatabaseConstants.FORMS_TABLE_NAME, null, values);
            db.setTransactionSuccessful();
            if (rowId > 0) {
                Uri formUri = Uri.withAppendedPath(
                        Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                        values.getAsString(FormsColumns.FORM_ID));
                getContext().getContentResolver().notifyChange(formUri, null);
                Uri idUri = Uri.withAppendedPath(
                        Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                        Long.toString(rowId));
                getContext().getContentResolver().notifyChange(idUri, null);

                return formUri;
            }
        } catch (Exception e) {
            log.w(t, "FAILED Insert into " + uri + " -- insert of row failed: " + e.toString());

            if (e instanceof SQLException) {
                throw (SQLException) e;
            } else {
                throw new SQLException(
                        "FAILED Insert into " + uri + " -- insert of row failed: " + e.toString());
            }
        }
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }

    throw new SQLException("Failed to insert row into " + uri);
}

From source file:org.pixmob.freemobile.netstat.SyncServiceTesting.java

private void run(Intent intent, final SQLiteDatabase db) throws Exception {
    final long now = dateAtMidnight(System.currentTimeMillis());

    Log.i(TAG, "Initializing statistics before uploading");

    final LongSparseArray<DailyStat> stats = new LongSparseArray<>(15);
    final Set<Long> uploadedStats = new HashSet<>(15);
    final long statTimestampStart = now - 7 * DAY_IN_MILLISECONDS;

    // Get pending uploads.
    Cursor pendingUploadsCursor = null;
    try {//from  w w w  .ja  v a 2  s.  c o m
        pendingUploadsCursor = db.query("daily_stat_testing",
                new String[] { "stat_timestamp", "orange", "free_mobile", "free_mobile_3g", "free_mobile_4g",
                        "free_mobile_femtocell", "sync" },
                "stat_timestamp>=? AND stat_timestamp<?",
                new String[] { String.valueOf(statTimestampStart), String.valueOf(now) }, null, null, null);
        while (pendingUploadsCursor.moveToNext()) {
            final long d = pendingUploadsCursor.getLong(0);
            final int sync = pendingUploadsCursor.getInt(6);
            if (SYNC_UPLOADED == sync) {
                uploadedStats.add(d);
            } else if (SYNC_PENDING == sync) {
                final DailyStat s = new DailyStat();
                s.orange = pendingUploadsCursor.getInt(1);
                s.freeMobile = pendingUploadsCursor.getInt(2);
                s.freeMobile3G = pendingUploadsCursor.getInt(3);
                s.freeMobile4G = pendingUploadsCursor.getInt(4);
                s.freeMobileFemtocell = pendingUploadsCursor.getInt(5);
                stats.put(d, s);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    } finally {
        try {
            if (pendingUploadsCursor != null)
                pendingUploadsCursor.close();
        } catch (Exception e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    }

    // Compute missing uploads.
    final ContentValues cv = new ContentValues();
    db.beginTransaction();
    try {
        for (long d = statTimestampStart; d < now; d += DAY_IN_MILLISECONDS) {
            if (stats.get(d) == null && !uploadedStats.contains(d)) {
                final DailyStat s = computeDailyStat(d);
                cv.put("stat_timestamp", d);
                cv.put("orange", s.orange);
                cv.put("free_mobile", s.freeMobile);
                cv.put("free_mobile_3g", s.freeMobile3G);
                cv.put("free_mobile_4g", s.freeMobile4G);
                cv.put("free_mobile_femtocell", s.freeMobileFemtocell);
                cv.put("sync", SYNC_PENDING);
                db.insertOrThrow("daily_stat_testing", null, cv);
                stats.put(d, s);
            }
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }

    // Delete old statistics.
    if (DEBUG) {
        Log.d(TAG, "Cleaning up upload database");
    }
    db.delete("daily_stat_testing", "stat_timestamp<?", new String[] { String.valueOf(statTimestampStart) });

    // Check if there are any statistics to upload.
    final int statsLen = stats.size();
    if (statsLen == 0) {
        Log.i(TAG, "Nothing to upload");
        return;
    }

    // Check if the remote server is up.
    final HttpClient client = createHttpClient();
    try {
        client.head(createServerUrl(null)).execute();
    } catch (HttpClientException e) {
        Log.w(TAG, "Remote server is not available: cannot upload statistics", e);
        return;
    }

    // Upload statistics.
    Log.i(TAG, "Uploading statistics");
    final JSONObject json = new JSONObject();
    final String deviceId = getDeviceId();
    final boolean deviceWasRegistered = intent.getBooleanExtra(EXTRA_DEVICE_REG, false);
    for (int i = 0; i < statsLen; ++i) {
        final long d = stats.keyAt(i);
        final DailyStat s = stats.get(d);

        try {
            json.put("timeOnOrange", s.orange);
            json.put("timeOnFreeMobile", s.freeMobile);
            json.put("timeOnFreeMobile3g", s.freeMobile3G);
            json.put("timeOnFreeMobile4g", s.freeMobile4G);
            json.put("timeOnFreeMobileFemtocell", s.freeMobileFemtocell);
        } catch (JSONException e) {
            final IOException ioe = new IOException("Failed to prepare statistics upload");
            ioe.initCause(e);
            throw ioe;
        }

        final String url = createServerUrl(
                "/device/" + deviceId + "/daily/" + DateFormat.format("yyyyMMdd", d));
        if (DEBUG) {
            Log.d(TAG, "Uploading statistics for " + DateUtils.formatDate(d) + " to: " + url);
        }

        final byte[] rawJson = json.toString().getBytes("UTF-8");
        try {
            client.post(url).content(rawJson, "application/json")
                    .expect(HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_NOT_FOUND)
                    .to(new HttpResponseHandler() {
                        @Override
                        public void onResponse(HttpResponse response) throws Exception {
                            final int sc = response.getStatusCode();
                            if (HttpURLConnection.HTTP_NOT_FOUND == sc) {
                                // Check if the device has just been
                                // registered.
                                if (deviceWasRegistered) {
                                    throw new IOException("Failed to upload statistics");
                                } else {
                                    // Got 404: the device does not exist.
                                    // We need to register this device.
                                    registerDevice(deviceId);

                                    // Restart this service.
                                    startService(new Intent(getApplicationContext(), SyncServiceTesting.class)
                                            .putExtra(EXTRA_DEVICE_REG, true));
                                }
                            } else if (HttpURLConnection.HTTP_OK == sc) {
                                // Update upload database.
                                cv.clear();
                                cv.put("sync", SYNC_UPLOADED);
                                db.update("daily_stat_testing", cv, "stat_timestamp=?",
                                        new String[] { String.valueOf(d) });

                                if (DEBUG) {
                                    Log.d(TAG, "Upload done for " + DateUtils.formatDate(d));
                                }
                            }
                        }
                    }).execute();
        } catch (HttpClientException e) {
            final IOException ioe = new IOException("Failed to send request with statistics");
            ioe.initCause(e);
            throw ioe;
        }
    }
}

From source file:com.newsrob.EntryManager.java

private void deleteArticlesFromDb(final SyncJob job, final List<String> articleIdsToDeleteInDatabase) {
    if (articleIdsToDeleteInDatabase.isEmpty())
        return;//from www  .  j a va  2s .  c  o  m

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

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

    SQLiteDatabase db = databaseHelper.getDb();

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

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

    try {

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

            db.beginTransaction();

            while (!articleIdsToDeleteInDatabase.isEmpty()) {

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

                job.actual++;

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

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

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

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

/**
 * This method removes the entry from the content provider, and also removes
 * any associated files. files: form.xml, [formmd5].formdef, formname
 * {directory}//from   w w w  .ja v  a  2  s. co m
 */
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() < 2 || segments.size() > 3) {
        throw new SQLException("Unknown URI (too many segments!) " + uri);
    }

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

    SQLiteDatabase db = null;
    List<IdStruct> idStructs = new ArrayList<IdStruct>();
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();

        boolean success = false;
        try {
            success = ODKDatabaseUtils.get().hasTableId(db, tableId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SQLException("Unknown URI (exception testing for tableId) " + uri);
        }
        if (!success) {
            throw new SQLException("Unknown URI (missing data table for tableId) " + uri);
        }

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

        if (segments.size() == 2) {
            where = "(" + where + ") AND (" + InstanceColumns.DATA_INSTANCE_ID + "=? )";
            if (whereArgs != null) {
                String[] args = new String[whereArgs.length + 1];
                for (int i = 0; i < whereArgs.length; ++i) {
                    args[i] = whereArgs[i];
                }
                args[whereArgs.length] = instanceId;
                whereArgs = args;
            } else {
                whereArgs = new String[] { instanceId };
            }
        }

        Cursor del = null;
        try {
            del = this.query(uri, null, where, whereArgs, null);
            del.moveToPosition(-1);
            while (del.moveToNext()) {
                String iId = ODKDatabaseUtils.get().getIndexAsString(del,
                        del.getColumnIndex(InstanceColumns._ID));
                String iIdDataTable = ODKDatabaseUtils.get().getIndexAsString(del,
                        del.getColumnIndex(InstanceColumns.DATA_INSTANCE_ID));
                idStructs.add(new IdStruct(iId, iIdDataTable));
                String path = ODKFileUtils.getInstanceFolder(appName, tableId, iIdDataTable);
                File f = new File(path);
                if (f.exists()) {
                    if (f.isDirectory()) {
                        FileUtils.deleteDirectory(f);
                    } else {
                        f.delete();
                    }
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new IllegalArgumentException("Unable to delete instance directory: " + e.toString());
        } finally {
            if (del != null) {
                del.close();
            }
        }

        for (IdStruct idStruct : idStructs) {
            db.delete(DatabaseConstants.UPLOADS_TABLE_NAME, InstanceColumns.DATA_INSTANCE_ID + "=?",
                    new String[] { idStruct.idUploadsTable });
            db.delete(dbTableName, DATA_TABLE_ID_COLUMN + "=?", new String[] { idStruct.idDataTable });
        }
        db.setTransactionSuccessful();
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return idStructs.size();
}

From source file:com.geecko.QuickLyric.tasks.WriteToDatabaseTask.java

@Override
public Boolean doInBackground(Object... params) {
    lyricsArray = new Lyrics[params.length - 2];
    SQLiteDatabase database;
    if (params[0] instanceof Fragment) {
        fragment = (Fragment) params[0];
        mContext = fragment.getActivity();
        if (mContext == null || !(mContext instanceof MainActivity))
            cancel(true);// w  ww.  j  a v a 2s .  c  o  m
        database = DatabaseHelper.getInstance(mContext).getWritableDatabase();
    } else
        database = (SQLiteDatabase) params[0];
    item = (MenuItem) params[1];
    if (params[2] instanceof Lyrics[])
        lyricsArray = (Lyrics[]) params[2];
    else
        for (int i = 0; i < lyricsArray.length; i++) {
            lyricsArray[i] = (Lyrics) params[i + 2];
        }
    boolean result = true;
    String[] columns = DatabaseHelper.columns;
    if (database != null && database.isOpen()) {
        database.beginTransaction();
        try {
            for (Lyrics lyrics : lyricsArray) {
                Lyrics storedLyrics = DatabaseHelper.getInstance(mContext)
                        .get(new String[] { lyrics.getArtist(), lyrics.getTitle(), lyrics.getOriginalArtist(),
                                lyrics.getOriginalTrack() });
                if ((storedLyrics == null || (!storedLyrics.isLRC() && lyrics.isLRC()))
                        && !"Storage".equals(lyrics.getSource())) {
                    ContentValues values = new ContentValues(2);
                    values.put(columns[0], lyrics.getArtist());
                    values.put(columns[1], lyrics.getTitle());
                    values.put(columns[2], lyrics.getText());
                    values.put(columns[3], lyrics.getURL());
                    values.put(columns[4], lyrics.getSource());
                    if (lyrics.getCoverURL() != null && lyrics.getCoverURL().startsWith("http://"))
                        values.put(columns[5], lyrics.getCoverURL());
                    values.put(columns[6], lyrics.getOriginalArtist());
                    values.put(columns[7], lyrics.getOriginalTrack());
                    values.put(columns[8], lyrics.isLRC() ? 1 : 0);
                    values.put(columns[9], lyrics.getWriter());
                    values.put(columns[10], lyrics.getCopyright());
                    database.delete(DatabaseHelper.TABLE_NAME,
                            String.format("%s=? AND %s=?", columns[0], columns[1]),
                            new String[] { lyrics.getArtist(), lyrics.getTitle() });
                    database.insert(DatabaseHelper.TABLE_NAME, null, values);
                    if (fragment instanceof LyricsViewFragment)
                        ((LyricsViewFragment) fragment).lyricsPresentInDB = true;
                    result = true;
                } else if (mContext != null) { // if called from activity, not service
                    database.delete(DatabaseHelper.TABLE_NAME,
                            String.format("%s=? AND %s=?", columns[0], columns[1]),
                            new String[] { lyrics.getArtist(), lyrics.getTitle() });
                    if (fragment instanceof LyricsViewFragment)
                        ((LyricsViewFragment) fragment).lyricsPresentInDB = false;
                    result = false;
                }
                database.yieldIfContendedSafely();
            }
            database.setTransactionSuccessful();
        } finally {
            database.endTransaction();
        }
    }
    return result;
}

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

/**
 * The deletion filter includes all non-null arguments. If all arguments
 * (except the db) are null, then all properties are removed.
 * //from ww w .j av  a 2s  . c  o m
 * @param db
 * @param tableId
 * @param partition
 * @param aspect
 * @param key
 */
public void deleteDBTableMetadata(SQLiteDatabase db, String tableId, String partition, String aspect,
        String key) {

    StringBuilder b = new StringBuilder();
    ArrayList<String> selArgs = new ArrayList<String>();
    if (tableId != null) {
        b.append(KeyValueStoreColumns.TABLE_ID).append("=?");
        selArgs.add(tableId);
    }
    if (partition != null) {
        if (b.length() != 0) {
            b.append(" AND ");
        }
        b.append(KeyValueStoreColumns.PARTITION).append("=?");
        selArgs.add(partition);
    }
    if (aspect != null) {
        if (b.length() != 0) {
            b.append(" AND ");
        }
        b.append(KeyValueStoreColumns.ASPECT).append("=?");
        selArgs.add(aspect);
    }
    if (key != null) {
        if (b.length() != 0) {
            b.append(" AND ");
        }
        b.append(KeyValueStoreColumns.KEY).append("=?");
        selArgs.add(key);
    }

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

        db.delete(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME, b.toString(),
                selArgs.toArray(new String[selArgs.size()]));

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

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

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

From source file:com.grazerss.EntryManager.java

private void deleteArticlesFromDb(final SyncJob job, final List<String> articleIdsToDeleteInDatabase) {
    if (articleIdsToDeleteInDatabase.isEmpty()) {
        return;/* w ww .  j  av  a  2 s  .  c om*/
    }

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

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

    SQLiteDatabase db = databaseHelper.getDb();

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

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

    try {

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

            db.beginTransaction();

            while (!articleIdsToDeleteInDatabase.isEmpty()) {

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

                job.actual++;

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

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

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

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

/**
 * Drop the given tableId and remove all the files (both configuration and
 * data attachments) associated with that table.
 * /*  w  ww.  j  av a  2  s.c o m*/
 * @param db
 * @param appName
 * @param tableId
 */
public void deleteDBTableAndAllData(SQLiteDatabase db, final String appName, final String tableId) {

    SyncETagsUtils seu = new SyncETagsUtils();
    boolean dbWithinTransaction = db.inTransaction();
    try {
        String whereClause = TableDefinitionsColumns.TABLE_ID + " = ?";
        String[] whereArgs = { tableId };

        if (!dbWithinTransaction) {
            db.beginTransaction();
        }

        // Drop the table used for the formId
        db.execSQL("DROP TABLE IF EXISTS \"" + tableId + "\";");

        // Delete the server sync ETags associated with this table
        seu.deleteAllSyncETags(db, tableId);

        // Delete the table definition for the tableId
        int count = db.delete(DatabaseConstants.TABLE_DEFS_TABLE_NAME, whereClause, whereArgs);

        // Delete the column definitions for this tableId
        db.delete(DatabaseConstants.COLUMN_DEFINITIONS_TABLE_NAME, whereClause, whereArgs);

        // Delete the uploads for the tableId
        String uploadWhereClause = InstanceColumns.DATA_TABLE_TABLE_ID + " = ?";
        db.delete(DatabaseConstants.UPLOADS_TABLE_NAME, uploadWhereClause, whereArgs);

        // Delete the values from the 4 key value stores
        db.delete(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME, whereClause, whereArgs);
        db.delete(DatabaseConstants.KEY_VALULE_STORE_SYNC_TABLE_NAME, whereClause, whereArgs);

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

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

    // And delete the files from the SDCard...
    String tableDir = ODKFileUtils.getTablesFolder(appName, tableId);
    try {
        FileUtils.deleteDirectory(new File(tableDir));
    } catch (IOException e1) {
        e1.printStackTrace();
        throw new IllegalStateException("Unable to delete the " + tableDir + " directory", e1);
    }

    String assetsCsvDir = ODKFileUtils.getAssetsFolder(appName) + "/csv";
    try {
        Collection<File> files = FileUtils.listFiles(new File(assetsCsvDir), new IOFileFilter() {

            @Override
            public boolean accept(File file) {
                String[] parts = file.getName().split("\\.");
                return (parts[0].equals(tableId) && parts[parts.length - 1].equals("csv")
                        && (parts.length == 2 || parts.length == 3
                                || (parts.length == 4 && parts[parts.length - 2].equals("properties"))));
            }

            @Override
            public boolean accept(File dir, String name) {
                String[] parts = name.split("\\.");
                return (parts[0].equals(tableId) && parts[parts.length - 1].equals("csv")
                        && (parts.length == 2 || parts.length == 3
                                || (parts.length == 4 && parts[parts.length - 2].equals("properties"))));
            }
        }, new IOFileFilter() {

            // don't traverse into directories
            @Override
            public boolean accept(File arg0) {
                return false;
            }

            // don't traverse into directories
            @Override
            public boolean accept(File arg0, String arg1) {
                return false;
            }
        });

        FileUtils.deleteDirectory(new File(tableDir));
        for (File f : files) {
            FileUtils.deleteQuietly(f);
        }
    } catch (IOException e1) {
        e1.printStackTrace();
        throw new IllegalStateException("Unable to delete the " + tableDir + " directory", e1);
    }
}