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:ru.orangesoftware.financisto2.db.DatabaseAdapter.java

private void runInTransaction(String sql, long[] ids) {
    SQLiteDatabase db = db();
    db.beginTransaction();/*w  w w  .  j ava2  s .c  om*/
    try {
        int count = ids.length;
        int bucket = 100;
        int num = 1 + count / bucket;
        for (int i = 0; i < num; i++) {
            int x = bucket * i;
            int y = Math.min(count, bucket * (i + 1));
            String script = createSql(sql, ids, x, y);
            db.execSQL(script);
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}

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

public void recalculateAccountsBalances() {
    SQLiteDatabase db = db();
    db.beginTransaction();//from w w w  . jav  a2  s .  c om
    try {
        Cursor accountsCursor = db.query(ACCOUNT_TABLE, new String[] { AccountColumns.ID }, null, null, null,
                null, null);
        try {
            while (accountsCursor.moveToNext()) {
                long accountId = accountsCursor.getLong(0);
                recalculateAccountBalances(accountId);
            }
        } finally {
            accountsCursor.close();
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}

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

public void purgeAccountAtDate(Account account, long date) {
    long nearestTransactionId = findNearestOlderTransactionId(account, date);
    if (nearestTransactionId > 0) {
        SQLiteDatabase db = db();
        db.beginTransaction();/*from w  w w .j  a  v  a 2 s .  c  o  m*/
        try {
            Transaction newTransaction = createTransactionFromNearest(account, nearestTransactionId);
            breakSplitTransactions(account, date);
            deleteOldTransactions(account, date);
            insertWithoutUpdatingBalance(newTransaction);
            db.execSQL(INSERT_RUNNING_BALANCE, new Object[] { account.id, newTransaction.id,
                    newTransaction.dateTime, newTransaction.fromAmount });
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    }
}

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

/**
 * mark given property of given article with given state
 *
 * @param id    set of article IDs, which should be processed
 * @param mark  mark to be set/*from  w ww. j  a  v  a  2 s .  com*/
 * @param state value for the mark
 */
public void markArticle(int id, String mark, int state) {
    if (!isDBAvailable())
        return;

    SQLiteDatabase db = getOpenHelper().getWritableDatabase();
    writeLock(true);
    db.beginTransaction();
    try {
        markArticles("" + id, mark, state);
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
        writeLock(false);
    }
}

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

/**
 * Extract POI data from a {@link JSONArray} of points of interest and add it to the POI table.
 *
 * @param data//www  .  jav  a 2 s  .  c  om
 */
public void loadPois(JSONArray data) throws JSONException {

    SQLiteDatabase db = this.getWritableDatabase();

    // empty the POI table to remove all existing data
    db.delete(TourContract.PoiEntry.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 point of interest in array
    for (int i = 0; i < DataStore.getAllCoupons().size(); i++) {
        Coupon coupon = DataStore.getAllCoupons().get(i);
        //Extract POI properties
        final String storeName = coupon.getStoreName();
        String details = coupon.getTitle();
        details = details.replace("<h1>", "").replace("</h1>", "");

        final Double lat = coupon.getLatitude();
        final Double lng = coupon.getLongitude();
        /* 
        /final String type = poi.getString("type");
         final String description = poi.getString("description");
         final String pictureUrl = poi.getString("pictureUrl");
         final String pictureAttr = poi.getString("pictureAttr");
                
         // Location
         JSONObject location = poi.getJSONObject("location");
         final double lat = location.getDouble("lat");
         final double lng = location.getDouble("lng");
         */
        // Create content values object for insert
        ContentValues cv = new ContentValues();
        cv.put(TourContract.PoiEntry.COLUMN_NAME_TITLE, storeName);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_TYPE, "LANDMARK");
        cv.put(TourContract.PoiEntry.COLUMN_NAME_DESCRIPTION, details);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_LOCATION_LAT, lat);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_LOCATION_LNG, lng);

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

    // All insert statement have been submitted, mark transaction as successful
    db.setTransactionSuccessful();

    if (db != null) {
        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);
    }/*from  w  ww .  j a  va  2  s. c  om*/

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

void insertArticles(Collection<Article> articles) {
    if (!isDBAvailable() || articles == null || articles.isEmpty())
        return;/*w  ww  .j  ava 2  s  . c  o  m*/

    SQLiteDatabase db = getOpenHelper().getWritableDatabase();
    writeLock(true);
    db.beginTransaction();
    try {
        for (Article a : articles) {
            insertArticleIntern(a);
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
        writeLock(false);
    }
}

From source file:net.zionsoft.obadiah.model.Bible.java

private void downloadTranslation(String url, String translationShortName, OnDownloadProgressListener onProgress)
        throws Exception {
    ZipInputStream zis = null;//from  ww  w .ja va  2  s .  c  om
    SQLiteDatabase db = null;
    try {
        db = mDatabaseHelper.openDatabase();
        if (db == null) {
            Analytics.trackException("Failed to open database.");
            throw new Exception("Failed to open database for writing");
        }
        db.beginTransaction();

        TranslationHelper.createTranslationTable(db, translationShortName);

        zis = new ZipInputStream(NetworkHelper.getStream(url));

        final byte buffer[] = new byte[2048];
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        int downloaded = 0;
        int read;
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            os.reset();
            while ((read = zis.read(buffer, 0, 2048)) != -1)
                os.write(buffer, 0, read);
            final byte[] bytes = os.toByteArray();
            String fileName = entry.getName();
            fileName = fileName.substring(0, fileName.length() - 5); // removes the trailing ".json"
            if (fileName.equals("books")) {
                TranslationHelper.saveBookNames(db, new JSONObject(new String(bytes, "UTF8")));
            } else {
                final String[] parts = fileName.split("-");
                final int bookIndex = Integer.parseInt(parts[0]);
                final int chapterIndex = Integer.parseInt(parts[1]);
                TranslationHelper.saveVerses(db, translationShortName, bookIndex, chapterIndex,
                        new JSONObject(new String(bytes, "UTF8")));
            }

            onProgress.onProgress(++downloaded / 12);
        }

        db.setTransactionSuccessful();
    } finally {
        if (db != null) {
            if (db.inTransaction()) {
                db.endTransaction();
            }
            mDatabaseHelper.closeDatabase();
        }
        if (zis != null) {
            try {
                zis.close();
            } catch (IOException e) {
                // we can't do much here
            }
        }
    }
}

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

void insertCategories(Set<Category> set) {
    if (!isDBAvailable() || set == null)
        return;/*from  ww w .  jav a2s. co m*/

    SQLiteDatabase db = getOpenHelper().getWritableDatabase();
    writeLock(true);
    db.beginTransaction();
    try {
        for (Category c : set) {
            insertCategory(c.id, c.title, c.unread);
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
        writeLock(false);
    }
}

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

void insertFeeds(Set<Feed> set) {
    if (!isDBAvailable() || set == null)
        return;/*w  w w .  jav a  2s. co m*/

    SQLiteDatabase db = getOpenHelper().getWritableDatabase();
    writeLock(true);
    db.beginTransaction();
    try {
        for (Feed f : set) {
            insertFeed(f.id, f.categoryId, f.title, f.url, f.unread);
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
        writeLock(false);
    }
}