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 long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes) {
    SQLiteDatabase db = db();
    db.beginTransaction();//from w ww  . jav a  2s.co  m
    try {
        long id = insertOrUpdateInTransaction(transaction, attributes);
        db.setTransactionSuccessful();
        return id;
    } finally {
        db.endTransaction();
    }
}

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

/**
 * Deletes the selected transactions//from  ww  w. jav  a  2  s .c  om
 *
 * @param ids selected transactions' ids
 */
public void deleteSelectedTransactions(long[] ids) {
    SQLiteDatabase db = db();
    db.beginTransaction();
    try {
        for (long id : ids) {
            deleteTransactionNoDbTransaction(id);
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}

From source file:com.google.android.apps.santatracker.service.APIProcessor.java

private int processStream(JSONArray json, boolean isWear) {
    SQLiteDatabase db = mStreamDBHelper.getWritableDatabase();

    db.beginTransaction();/*  ww  w.  java 2  s.c om*/
    try {
        // loop over each card

        int i;
        for (i = 0; i < json.length(); i++) {
            JSONObject card = json.getJSONObject(i);

            final long timestamp = card.getLong(FIELD_STREAM_TIMESTAMP);
            final String status = getExistingJSONString(card, FIELD_STREAM_STATUS);
            final String didYouKnow = getExistingJSONString(card, FIELD_STREAM_DIDYOUKNOW);
            final String imageUrl = getExistingJSONString(card, FIELD_STREAM_IMAGEURL);
            final String youtubeId = getExistingJSONString(card, FIELD_STREAM_YOUTUBEID);

            //                if (mDebugLog) {
            //                    Log.d(TAG, "Notification: " + timestamp);
            //                }

            try {
                // All parsed, insert into DB
                mStreamDBHelper.insert(db, timestamp, status, didYouKnow, imageUrl, youtubeId, isWear);
            } catch (android.database.sqlite.SQLiteConstraintException e) {
                // ignore duplicate cards
            }
        }

        db.setTransactionSuccessful();
        return i;
    } catch (JSONException e) {
        Log.d(TAG, "Santa location tracking error 31");
        SantaLog.d(TAG, "JSON Exception", e);
    } finally {
        db.endTransaction();
    }

    return 0;
}

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

public void saveDownloadedRates(List<ExchangeRate> downloadedRates) {
    SQLiteDatabase db = db();
    db.beginTransaction();/*w ww  .j av a2 s  . c o  m*/
    try {
        for (ExchangeRate r : downloadedRates) {
            if (r.isOk()) {
                replaceRateInTransaction(r, r.date, db);
            }
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}

From source file:org.ohmage.db.DbHelper.java

/**
 * Used by the ContentProvider to insert a campaign and also insert into
 * interested tables. Don't use this directly; if you do, none of the
 * contentobservers, etc. that are listening to Campaigns, Surveys, or
 * SurveyPrompts will be notified.//from  w  ww .j  a  v a  2 s  . co  m
 * 
 * @param values
 *            a ContentValues collection, preferably generated by calling
 *            {@link Campaign}'s toCV() method
 * @return the ID of the inserted record
 */
public long addCampaign(SQLiteDatabase db, ContentValues values) {

    long rowId = -1; // the row ID for the campaign that we'll eventually be
                     // returning

    try {
        // start the transaction that will include inserting the campaign +
        // surveys + survey prompts
        db.beginTransaction();

        // hold onto some variables for processing
        String configurationXml = values.getAsString(Campaigns.CAMPAIGN_CONFIGURATION_XML);
        String campaignUrn = values.getAsString(Campaigns.CAMPAIGN_URN);

        // actually insert the campaign
        rowId = db.insert(Tables.CAMPAIGNS, null, values);

        if (configurationXml != null) {
            // xml parsing below, inserts into Surveys and SurveyPrompts
            if (populateSurveysFromCampaignXML(db, campaignUrn, configurationXml)) {
                // i think we're done now; finish up the transaction
                db.setTransactionSuccessful();
            }
            // else we fail and the transaction gets rolled back
        } else {
            db.setTransactionSuccessful();
        }
    } finally {
        db.endTransaction();
    }

    return rowId;
}

From source file:it.bradipao.berengar.DbTool.java

public static int json2table(SQLiteDatabase mDB, JSONObject jsonTable) {

    // vars/*from w w w . j av  a2 s . c  o  m*/
    JSONArray jsonRows = new JSONArray();
    JSONArray jsonColsName = new JSONArray();
    JSONArray jsonCols = null;
    ContentValues cv = null;

    int iRes = 0;
    try {
        // init database transaction
        mDB.beginTransaction();
        // fetch table name and drop if exists
        String sTableName = jsonTable.getString("table_name");
        mDB.execSQL("DROP TABLE IF EXISTS " + sTableName);
        if (GOLOG)
            Log.d(LOGTAG, "TABLE NAME : " + sTableName);
        // fetch and execute create sql
        String sTableSql = jsonTable.getString("table_sql");
        mDB.execSQL(sTableSql);
        // fetch columns name
        jsonColsName = jsonTable.getJSONArray("cols_name");
        // fetch rows array
        jsonRows = jsonTable.getJSONArray("rows");
        // iterate through rows
        for (int i = 0; i < jsonRows.length(); i++) {
            // fetch columns
            jsonCols = jsonRows.getJSONArray(i);
            // perform insert
            cv = new ContentValues();
            for (int j = 0; j < jsonCols.length(); j++)
                cv.put(jsonColsName.getString(j), jsonCols.getString(j));
            mDB.insert(sTableName, null, cv);
            if (GOLOG)
                Log.d(LOGTAG, "INSERT IN " + sTableName + " ID=" + jsonCols.getString(0));
        }
        iRes++;
        // set transaction successful
        mDB.setTransactionSuccessful();
    } catch (Exception e) {
        Log.e(LOGTAG, "error in json2table", e);
    } finally {
        // end transaction, commit if successful else rollback
        mDB.endTransaction();
    }

    return iRes;
}

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

/**
 * Extract POI data from a {@link JSONArray} of points of interest and add
 * it to the POI table./*  w  ww .j  a va 2  s  .  c o  m*/
 * 
 * @param data
 */
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 < data.length(); i++) {
        JSONObject poi = data.getJSONObject(i);

        // Extract POI properties
        final String title = poi.getString("title");
        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, title);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_TYPE, type);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_DESCRIPTION, description);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_PICTURE_URL, pictureUrl);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_LOCATION_LAT, lat);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_LOCATION_LNG, lng);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_PICTURE_ATTR, pictureAttr);

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

private void runInTransaction(String sql, long[] ids) {
    SQLiteDatabase db = db();
    db.beginTransaction();//  w  w  w  .j a  v  a2  s .com
    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:com.osfans.trime.DictionaryHelper.java

private boolean importDict(InputStream is) {
    boolean success = false;
    SQLiteDatabase db = getWritableDatabase();
    db.beginTransaction();/*from w  ww. j  a  v  a2s .c  om*/
    try {
        String line;
        StringBuilder content = new StringBuilder();
        InputStreamReader ir = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(ir);
        while ((line = br.readLine()) != null && !line.contentEquals(fs)) {
            content.append(line);
            content.append(newline);
        }

        Yaml yaml = new Yaml();
        Map<String, Object> y = (Map<String, Object>) (yaml.load(content.toString()));
        String table = (String) y.get("name");

        db.execSQL("DROP TABLE IF EXISTS " + table);
        db.execSQL(String.format("CREATE VIRTUAL TABLE %s USING fts3(hz, py)", table));

        ContentValues initialValues = new ContentValues(2);
        int max = is.available();
        int progress = 0;
        int count = 0;
        while ((line = br.readLine()) != null) {
            if (line.startsWith(comment))
                continue;
            String[] s = line.split("\t");
            if (s.length < 2)
                continue;
            initialValues.put("hz", s[0]);
            initialValues.put("py", s[1]);
            db.insert(table, null, initialValues);
            initialValues.clear();
            count++;
            if ((count % 1000) == 0) {
                progress = max - is.available();
                mBuilder.setProgress(max, progress, false)
                        .setContentText(String.format("%d / 100", progress * 100 / max));
                mNotifyManager.notify(notify_id, mBuilder.build());
            }
        }
        is.close();
        db.setTransactionSuccessful();
        success = true;
    } catch (Exception e) {
        throw new RuntimeException("Error import dict", e);
    } finally {
        db.endTransaction();
        mNotifyManager.cancel(notify_id);
    }
    return success;
}

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

public void recalculateAccountsBalances() {
    SQLiteDatabase db = db();
    db.beginTransaction();//  ww w.j a v a2s  .  c o m
    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();
    }
}