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: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  ww .  ja v a2 s.  co 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  .  ja  va 2s .  c  o m*/
 * @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:org.ohmage.db.DbHelper.java

/**
 * Adds a response to the feedback database.
 * //from w ww. j av a2s.c  o  m
 * @return the ID of the inserted record, or -1 if unsuccessful
 */
public long addResponseRow(SQLiteDatabase db, ContentValues values) {
    long rowId = -1;

    // extract data that we'll need to parse the json + insert prompt
    // responses
    String response = values.getAsString(Responses.RESPONSE_JSON);
    String campaignUrn = values.getAsString(Responses.CAMPAIGN_URN);
    String surveyId = values.getAsString(Responses.SURVEY_ID);

    try {
        // start a transaction involving the following operations:
        // 1) insert feedback response row
        // 2) parse json-encoded responses and insert one row into prompts
        // per entry
        db.beginTransaction();

        // do the actual insert into feedback responses
        rowId = db.insert(Tables.RESPONSES, null, values);

        // check if it succeeded; if not, we can't do anything
        if (rowId == -1)
            return -1;

        if (populatePromptsFromResponseJSON(db, rowId, response, campaignUrn, surveyId)) {
            // and we're done; finalize the transaction
            db.setTransactionSuccessful();
        }
        // else we fail and the transaction gets rolled back
    } catch (SQLiteConstraintException e) {
        Log.e(TAG, "Attempted to insert record that violated a SQL constraint (likely the hashcode)");
        return -1;
    } catch (Exception e) {
        Log.e(TAG, "Generic exception thrown from db insert", e);
        return -1;
    } finally {
        db.endTransaction();
        // db.close();
    }

    return rowId;
}

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/*from  ww w  .j a v  a2 s.  c  o m*/
 */
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.ttrssreader.controllers.DBHelper.java

void insertArticles(Collection<Article> articles) {
    if (!isDBAvailable() || articles == null || articles.isEmpty())
        return;/* w w  w.  j av  a 2  s  .c om*/

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

void insertCategories(Set<Category> set) {
    if (!isDBAvailable() || set == null)
        return;//from  w  w  w.  j av a2s  .  com

    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. j a  v 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);
    }
}

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// w ww. jav 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: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 .j a va  2  s  . c  om
        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:net.zionsoft.obadiah.model.Bible.java

private void downloadTranslation(String url, String translationShortName, OnDownloadProgressListener onProgress)
        throws Exception {
    ZipInputStream zis = null;//  w w  w. j  a v a  2s  .com
    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
            }
        }
    }
}