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.ttrssreader.controllers.DBHelper.java

/**
 * insert given remote files into DB and link them with given article
 *
 * @param articleId "parent" article//from   ww  w  .ja v a  2  s.co m
 * @param fileUrls  array of remote file URLs
 */
public void insertArticleFiles(int articleId, String[] fileUrls) {
    if (!isDBAvailable())
        return;

    SQLiteDatabase db = getOpenHelper().getWritableDatabase();
    writeLock(true);
    db.beginTransaction();
    try {
        for (String url : fileUrls) {
            long remotefileId = insertRemoteFile(url);
            if (remotefileId != 0)
                insertRemoteFile2Article(remotefileId, articleId);
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
        writeLock(false);
    }
}

From source file:org.ttrssreader.controllers.DBHelper.java

/**
 * mark given remote file as cached/uncached and optionally specify it's file size
 *
 * @param url    remote file URL//from w  ww .  j  a  v  a  2 s . co m
 * @param cached the cached flag
 * @param size   file size may be {@code null}, if so, then it will not be updated in DB
 */
public void markRemoteFileCached(String url, boolean cached, Long size) {
    if (!isDBAvailable())
        return;

    SQLiteDatabase db = getOpenHelper().getWritableDatabase();
    writeLock(true);
    db.beginTransaction();
    try {
        ContentValues cv = new ContentValues(2);
        cv.put("cached", cached);
        if (size != null) {
            cv.put("length", size);
        }
        db.update(TABLE_REMOTEFILES, cv, "url=?", new String[] { url });
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
        writeLock(false);
    }
}

From source file:org.ttrssreader.controllers.DBHelper.java

/**
 * mark remote files with given IDs as non cached (cached=0)
 *
 * @param rfIds IDs of remote files to be marked as non-cached
 *//*from w  w  w .jav a2 s .  c o m*/
public void markRemoteFilesNonCached(Collection<Integer> rfIds) {
    if (!isDBAvailable())
        return;

    SQLiteDatabase db = getOpenHelper().getWritableDatabase();
    writeLock(true);
    db.beginTransaction();
    try {
        ContentValues cv = new ContentValues(1);
        cv.put("cached", 0);
        for (String ids : StringSupport.convertListToString(rfIds, 1000)) {
            db.update(TABLE_REMOTEFILES, cv, "id in (" + ids + ")", null);
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
        writeLock(false);
    }
}

From source file:org.pixmob.freemobile.netstat.SyncService.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<DailyStat>(15);
    final Set<Long> uploadedStats = new HashSet<Long>(15);
    final long statTimestampStart = now - 7 * DAY_IN_MILLISECONDS;

    // Get pending uploads.
    Cursor c = db.query("daily_stat", new String[] { "stat_timestamp", "orange", "free_mobile", "sync" },
            "stat_timestamp>=? AND stat_timestamp<?",
            new String[] { String.valueOf(statTimestampStart), String.valueOf(now) }, null, null, null);
    try {/*  w  ww .  j a va 2 s.  c  om*/
        while (c.moveToNext()) {
            final long d = c.getLong(0);
            final int sync = c.getInt(3);
            if (SYNC_UPLOADED == sync) {
                uploadedStats.add(d);
            } else if (SYNC_PENDING == sync) {
                final DailyStat s = new DailyStat();
                s.orange = c.getInt(1);
                s.freeMobile = c.getInt(2);
                stats.put(d, s);
            }
        }
    } finally {
        c.close();
    }

    // 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("sync", SYNC_PENDING);
                db.insertOrThrow("daily_stat", 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", "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);
        } 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(), SyncService.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", 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:ru.orangesoftware.financisto2.db.DatabaseAdapter.java

public int deleteAccount(long id) {
    SQLiteDatabase db = db();
    db.beginTransaction();/*from ww w.  j  a v a2  s.com*/
    try {
        String[] sid = new String[] { String.valueOf(id) };
        Account a = load(Account.class, id);
        writeDeleteLog(TRANSACTION_TABLE, a.remoteKey);
        db.execSQL(UPDATE_ORPHAN_TRANSACTIONS_1, sid);
        db.execSQL(UPDATE_ORPHAN_TRANSACTIONS_2, sid);
        db.delete(TRANSACTION_ATTRIBUTE_TABLE,
                TransactionAttributeColumns.TRANSACTION_ID + " in (SELECT _id from " + TRANSACTION_TABLE
                        + " where " + TransactionColumns.from_account_id + "=?)",
                sid);
        db.delete(TRANSACTION_TABLE, TransactionColumns.from_account_id + "=?", sid);
        int count = db.delete(ACCOUNT_TABLE, "_id=?", sid);
        db.setTransactionSuccessful();
        return count;
    } finally {
        db.endTransaction();
    }

}

From source file:org.ttrssreader.controllers.DBHelper.java

void markUnsynchronizedNotes(Map<Integer, String> ids) {
    if (!isDBAvailable())
        return;/*from   www  .  j  a v a  2 s.co m*/

    SQLiteDatabase db = getOpenHelper().getWritableDatabase();
    writeLock(true);
    db.beginTransaction();
    try {
        for (Integer id : ids.keySet()) {
            String note = ids.get(id);
            if (note == null || note.equals(""))
                continue;

            ContentValues cv = new ContentValues(1);
            cv.put(MARK_NOTE, note);
            db.update(TABLE_MARK, cv, "id=" + id, null);
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
        writeLock(false);
    }
}

From source file:org.ttrssreader.controllers.DBHelper.java

/**
 * delete articles and all its resources (e.g. remote files, labels etc.)
 *
 * @param whereClause the optional WHERE clause to apply when deleting.
 *                    Passing null will delete all rows.
 * @param whereArgs   You may include ?s in the where clause, which
 *                    will be replaced by the values from whereArgs. The values
 *                    will be bound as Strings.
 * @return the number of rows affected if a whereClause is passed in, 0
 * otherwise. To remove all rows and get a count pass "1" as the
 * whereClause.//from   ww  w. j  a  v a 2 s .com
 */
private int safelyDeleteArticles(String whereClause, String[] whereArgs) {
    int deletedCount = 0;

    Collection<RemoteFile> rfs = getRemoteFilesForArticles(whereClause, whereArgs, true);
    if (!rfs.isEmpty()) {
        Set<Integer> rfIds = new HashSet<>(rfs.size());
        for (RemoteFile rf : rfs) {
            rfIds.add(rf.id);
            Controller.getInstance().getImageCache().getCacheFile(rf.url).delete();
        }
        deleteRemoteFiles(rfIds);
    }

    // @formatter:off
    StringBuilder query = new StringBuilder();
    query.append(" articleId IN (").append("     SELECT _id").append("       FROM ").append(TABLE_ARTICLES)
            .append("       WHERE ").append(whereClause).append(" )");
    // @formatter:on

    SQLiteDatabase db = getOpenHelper().getWritableDatabase();
    writeLock(true);
    db.beginTransaction();
    try {
        // first, delete article referencies from linking table to preserve foreign key constraint on the next step
        db.delete(TABLE_REMOTEFILE2ARTICLE, query.toString(), whereArgs);

        // TODO Foreign-key constraint failed from purgeOrphanedArticles() and safelyDeleteArticles()
        deletedCount = db.delete(TABLE_ARTICLES, whereClause, whereArgs);
        purgeLabels();
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
        writeLock(false);
    }

    return deletedCount;
}

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

private void rawDeleteDataInDBTable(SQLiteDatabase db, String tableId, String whereClause, String[] whereArgs) {
    boolean dbWithinTransaction = db.inTransaction();
    try {/*w  ww  .java2  s.c  o m*/
        if (!dbWithinTransaction) {
            db.beginTransaction();
        }

        db.delete(tableId, whereClause, whereArgs);

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

From source file:org.ttrssreader.controllers.DBHelper.java

void markUnsynchronizedStates(Collection<Integer> ids, String mark, int state) {
    if (!isDBAvailable())
        return;//from   w w  w  .j a va  2 s.  co m

    SQLiteDatabase db = getOpenHelper().getWritableDatabase();
    writeLock(true);
    db.beginTransaction();
    try {
        for (Integer id : ids) {
            // First update, then insert. If row exists it gets updated and second call ignores it, else the second
            // call inserts it.
            db.execSQL(String.format("UPDATE %s SET %s=%s WHERE id=%s", TABLE_MARK, mark, state, id));
            db.execSQL(String.format("INSERT OR IGNORE INTO %s (id, %s) VALUES (%s, %s)", TABLE_MARK, mark, id,
                    state));
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
        writeLock(false);
    }
}

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

public long[] storeMissedSchedules(List<RestoredTransaction> restored, long now) {
    SQLiteDatabase db = db();
    db.beginTransaction();// w ww  .j  ava2 s.co  m
    try {
        int count = restored.size();
        long[] restoredIds = new long[count];
        HashMap<Long, Transaction> transactions = new HashMap<Long, Transaction>();
        for (int i = 0; i < count; i++) {
            RestoredTransaction rt = restored.get(i);
            long transactionId = rt.transactionId;
            Transaction t = transactions.get(transactionId);
            if (t == null) {
                t = getTransaction(transactionId);
                transactions.put(transactionId, t);
            }
            t.id = -1;
            t.dateTime = rt.dateTime.getTime();
            t.status = TransactionStatus.RS;
            t.isTemplate = 0;
            restoredIds[i] = insertOrUpdate(t);
            t.id = transactionId;
        }
        for (Transaction t : transactions.values()) {
            db.execSQL(UPDATE_LAST_RECURRENCE, new Object[] { now, t.id });
        }
        db.setTransactionSuccessful();
        return restoredIds;
    } finally {
        db.endTransaction();
    }
}