Example usage for android.database.sqlite SQLiteDatabase setTransactionSuccessful

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

Introduction

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

Prototype

public void setTransactionSuccessful() 

Source Link

Document

Marks the current transaction as successful.

Usage

From source file:mobisocial.musubi.ui.AcceptFriendActivity.java

@Override
protected void onResume() {
    super.onResume();
    if (getIntent() == null || getIntent().getData() == null) {
        Toast.makeText(this, "No data.", Toast.LENGTH_SHORT).show();
        finish();/*w w w . ja va  2 s.c  o m*/
        return;
    }
    mUri = getIntent().getData();
    mName = mUri.getQueryParameter("n");
    if (mName == null) {
        mName = "Unnamed Friend";
    }

    mTypes = mUri.getQueryParameters("t");
    mPrincipals = mUri.getQueryParameters("p");

    if (mTypes.size() != mPrincipals.size()) {
        Toast.makeText(this, "Mismatched identity information", Toast.LENGTH_SHORT).show();
        finish();
        return;
    }
    if (mTypes.size() == 0) {
        Toast.makeText(this, "Missing identity information", Toast.LENGTH_SHORT).show();
        finish();
        return;
    }

    Iterator<String> i_types = mTypes.iterator();
    Iterator<String> i_princiapls = mPrincipals.iterator();

    TLongArrayList ids = new TLongArrayList(4);
    SQLiteDatabase db = mDatabaseSource.getWritableDatabase();
    int num_facebook_ids = 0;
    String description = "";
    try {
        db.beginTransaction();
        while (i_types.hasNext()) {
            int type;
            try {
                type = Integer.parseInt(i_types.next());
            } catch (NumberFormatException e) {
                continue;
            }
            String principal = i_princiapls.next();
            Authority authority = IBHashedIdentity.Authority.values()[type];
            if (authority == Authority.Local) {
                continue;
            }
            IBIdentity id = new IBIdentity(authority, principal, 0);

            long identId = mIdentitiesManager.getIdForIBHashedIdentity(id);
            MIdentity ident;
            if (identId == 0) {
                ident = new MIdentity();
                ident.type_ = authority;
                ident.principal_ = principal;
                ident.principalHash_ = Util.sha256(ident.principal_.getBytes());
                ident.principalShortHash_ = Util.shortHash(ident.principalHash_);
                ident.claimed_ = true;
                ident.musubiName_ = mName;
                identId = mIdentitiesManager.insertIdentity(ident);
            } else {
                ident = mIdentitiesManager.getIdentityForId(identId);
                ident.principal_ = principal; // implicitly checked by lookup
                ident.claimed_ = true;
                ident.musubiName_ = mName;
                mIdentitiesManager.updateIdentity(ident);
            }
            ids.add(identId);
            if (ident.type_ == Authority.Facebook) {
                num_facebook_ids++;
            } else {
                description += "\n" + ident.principal_;
            }
        }
        if (num_facebook_ids > 0) {
            description += "\n" + num_facebook_ids + " Facebook IDs";
        }
        db.setTransactionSuccessful();
    } catch (Exception e) {
    } finally {
        db.endTransaction();
    }

    showDialog(AcceptFriendDialog.newInstance(mName, description, ids.toArray()));
}

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

/**
 * mark given property of given articles with given state
 *
 * @param idList set of article IDs, which should be processed
 * @param mark   mark to be set// ww  w.  j av  a2  s  . c  o m
 * @param state  value for the mark
 */
public void markArticles(Set<Integer> idList, String mark, int state) {
    if (!isDBAvailable())
        return;

    if (idList != null && !idList.isEmpty()) {
        SQLiteDatabase db = getOpenHelper().getWritableDatabase();
        writeLock(true);
        db.beginTransaction();
        try {
            for (String ids : StringSupport.convertListToString(idList, 400)) {
                markArticles(ids, mark, state);
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            writeLock(false);
        }
    }
}

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

/**
 * insert given remote files into DB and link them with given article
 *
 * @param articleId "parent" article/*  w  w w  .j  av  a2 s .  c o 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 ava2 s .  c om
 * @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 .  j a v a  2 s .  co 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:ru.orangesoftware.financisto2.db.DatabaseAdapter.java

public int deleteAccount(long id) {
    SQLiteDatabase db = db();
    db.beginTransaction();/*from www .j av  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.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 {//from w w  w.  jav  a  2 s  .co  m
        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:org.ttrssreader.controllers.DBHelper.java

void markUnsynchronizedNotes(Map<Integer, String> ids) {
    if (!isDBAvailable())
        return;//w  ww.  ja  v a2  s .c  o 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.opendatakit.common.android.utilities.ODKDatabaseUtils.java

private void rawDeleteDataInDBTable(SQLiteDatabase db, String tableId, String whereClause, String[] whereArgs) {
    boolean dbWithinTransaction = db.inTransaction();
    try {//w  ww  .ja  v  a  2 s .  co 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

/**
 * 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 w  w  w  .j  a  v  a  2 s . co  m*/
 */
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;
}