Example usage for android.database.sqlite SQLiteDatabase beginTransaction

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

Introduction

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

Prototype

public void beginTransaction() 

Source Link

Document

Begins a transaction in EXCLUSIVE mode.

Usage

From source file:org.jumpmind.symmetric.android.AndroidSqlTemplate.java

public int update(final boolean autoCommit, final boolean failOnError, boolean failOnDrops,
        boolean failOnSequenceCreate, final int commitRate, final ISqlResultsListener resultsListener,
        final ISqlStatementSource source) {
    int row = 0;/*from   ww  w . j a va  2  s. c o  m*/
    SQLiteDatabase database = this.databaseHelper.getWritableDatabase();
    String currentStatement = null;
    try {
        if (!autoCommit) {
            database.beginTransaction();
        }

        for (String statement = source.readSqlStatement(); statement != null; statement = source
                .readSqlStatement()) {
            currentStatement = statement;
            update(statement);
            row++;
            if (!autoCommit && row % commitRate == 0) {
                database.setTransactionSuccessful();
                database.endTransaction();
                database.beginTransaction();
            }

            if (resultsListener != null) {
                resultsListener.sqlApplied(statement, row, 0, row);
            }
        }

        if (!autoCommit) {
            database.setTransactionSuccessful();
        }
    } catch (RuntimeException ex) {
        if (resultsListener != null) {
            resultsListener.sqlErrored(currentStatement, translate(currentStatement, ex), row, false, false);
        }
        throw ex;
    } finally {
        if (!autoCommit) {
            database.endTransaction();
        }

        close(database);
    }

    return row;
}

From source file:com.digicorp.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Executes a batch request and sends the results via sendJavascriptCB().
 *
 * @param dbname/*from w  w  w  .  j ava  2s.  c o  m*/
 *            The name of the database.
 *
 * @param queryarr
 *            Array of query strings
 *
 * @param jsonparams
 *            Array of JSON query parameters
 *
 * @param queryIDs
 *            Array of query ids
 *
 * @param tx_id
 *            Transaction id
 *
 */
private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonparams, String[] queryIDs,
        String tx_id) {
    SQLiteDatabase mydb = this.getDatabase(dbname);

    if (mydb == null)
        return;

    try {
        mydb.beginTransaction();

        String query = "";
        String query_id = "";
        int len = queryarr.length;

        for (int i = 0; i < len; i++) {
            query = queryarr[i];
            query_id = queryIDs[i];
            if (query.toLowerCase().startsWith("insert") && jsonparams != null) {
                SQLiteStatement myStatement = mydb.compileStatement(query);
                for (int j = 0; j < jsonparams[i].length(); j++) {
                    if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double) {
                        myStatement.bindDouble(j + 1, jsonparams[i].getDouble(j));
                    } else if (jsonparams[i].get(j) instanceof Number) {
                        myStatement.bindLong(j + 1, jsonparams[i].getLong(j));
                    } else if (jsonparams[i].isNull(j)) {
                        myStatement.bindNull(j + 1);
                    } else {
                        myStatement.bindString(j + 1, jsonparams[i].getString(j));
                    }
                }
                long insertId = myStatement.executeInsert();

                String result = "{'insertId':'" + insertId + "'}";
                this.sendJavascriptCB("window.SQLitePluginTransactionCB.queryCompleteCallback('" + tx_id + "','"
                        + query_id + "', " + result + ");");
            } else {
                String[] params = null;

                if (jsonparams != null) {
                    params = new String[jsonparams[i].length()];

                    for (int j = 0; j < jsonparams[i].length(); j++) {
                        if (jsonparams[i].isNull(j))
                            params[j] = "";
                        else
                            params[j] = jsonparams[i].getString(j);
                    }
                }

                Cursor myCursor = mydb.rawQuery(query, params);

                if (query_id.length() > 0)
                    this.processResults(myCursor, query_id, tx_id);

                myCursor.close();
            }
        }
        mydb.setTransactionSuccessful();
    } catch (SQLiteException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } catch (JSONException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } finally {
        mydb.endTransaction();
        Log.v("executeSqlBatch", tx_id);
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txCompleteCallback('" + tx_id + "');");
    }
}

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

/**
 * Extract Route data from a {@link JSONArray} of save it in the database.
 * // w  w w .j a  v  a  2s .  c o m
 * @param data
 */
public void loadRoute(JSONArray data) throws JSONException {

    SQLiteDatabase db = this.getWritableDatabase();

    // Empty the route table to remove all existing data
    db.delete(TourContract.RouteEntry.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 location in array
    for (int i = 0; i < data.length(); i++) {
        // extract data
        JSONObject poi = data.getJSONObject(i);
        final double lat = poi.getDouble("lat");
        final double lng = poi.getDouble("lng");

        // Construct insert statement
        ContentValues cv = new ContentValues();
        cv.put(TourContract.RouteEntry.COLUMN_NAME_LAT, lat);
        cv.put(TourContract.RouteEntry.COLUMN_NAME_LNG, lng);

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

    if (db != null) {
        // All insert statement have been submitted, mark transaction as
        // successful
        db.setTransactionSuccessful();
        db.endTransaction();
    }
}

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

/**
 * Extract Route data from a {@link JSONArray} of save it in the database.
 *
 * @param data//from w ww  . java2 s .c  o m
 */
public void loadRoute(JSONArray data) throws JSONException {

    SQLiteDatabase db = this.getWritableDatabase();

    // Empty the route table to remove all existing data
    db.delete(TourContract.RouteEntry.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 location in array
    for (int i = 0; i < data.length(); i++) {
        // extract data
        JSONObject poi = data.getJSONObject(i);
        final double lat = poi.getDouble("lat");
        final double lng = poi.getDouble("lng");

        // Construct insert statement
        ContentValues cv = new ContentValues();
        cv.put(TourContract.RouteEntry.COLUMN_NAME_LAT, lat);
        cv.put(TourContract.RouteEntry.COLUMN_NAME_LNG, lng);

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

    if (db != null) {
        // All insert statement have been submitted, mark transaction as successful
        db.setTransactionSuccessful();
        db.endTransaction();
    }
}

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.//from  ww  w  .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: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//  w  ww. j  av  a2s  .  com
 */
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:com.wheelermarine.publicAccessSites.Updater.java

@Override
protected Integer doInBackground(URL... urls) {

    try {/*from   w ww  . j av a2 s .  c o  m*/
        final DatabaseHelper db = new DatabaseHelper(context);

        SQLiteDatabase database = db.getWritableDatabase();
        if (database == null)
            throw new IllegalStateException("Unable to open database!");

        database.beginTransaction();
        try {
            // Clear out the old data.
            database.delete(DatabaseHelper.PublicAccessEntry.TABLE_NAME, null, null);

            // Connect to the web server and locate the FTP download link.
            Log.v(TAG, "Finding update: " + urls[0]);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progress.setMessage("Locating update...");
                    progress.setIndeterminate(true);
                }
            });
            Document doc = Jsoup.connect(urls[0].toString()).timeout(timeout * 1000).userAgent(userAgent).get();
            URL dataURL = null;
            for (Element element : doc.select("a")) {
                if (element.hasAttr("href") && element.attr("href").endsWith(".zip")) {
                    dataURL = new URL(element.attr("href"));
                }
            }

            // Make sure the download URL was fund.
            if (dataURL == null)
                throw new FileNotFoundException("Unable to locate data URL.");

            // Connect to the FTP server and download the update.
            Log.v(TAG, "Downloading update: " + dataURL);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progress.setMessage("Downloading update...");
                    progress.setIndeterminate(true);
                }
            });
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(dataURL.toString());
            HttpResponse response = client.execute(get);
            HttpEntity entity = response.getEntity();
            if (entity == null)
                throw new IOException("Error downloading update.");

            Map<Integer, Location> locations = null;

            // Download the ZIP archive.
            Log.v(TAG, "Downloading: " + dataURL.getFile());
            InputStream in = entity.getContent();
            if (in == null)
                throw new FileNotFoundException(dataURL.getFile() + " was not found!");
            try {
                ZipInputStream zin = new ZipInputStream(in);
                try {
                    // Locate the .dbf entry in the ZIP archive.
                    ZipEntry entry;
                    while ((entry = zin.getNextEntry()) != null) {
                        if (entry.getName().endsWith(entryName)) {
                            readDBaseFile(zin, database);
                        } else if (entry.getName().endsWith(shapeEntryName)) {
                            locations = readShapeFile(zin);
                        }
                    }
                } finally {
                    try {
                        zin.close();
                    } catch (Exception e) {
                        // Ignore this error.
                    }
                }
            } finally {
                in.close();
            }

            if (locations != null) {
                final int recordCount = locations.size();
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progress.setIndeterminate(false);
                        progress.setMessage("Updating locations...");
                        progress.setMax(recordCount);
                    }
                });

                int progress = 0;
                for (int recordNumber : locations.keySet()) {
                    PublicAccess access = db.getPublicAccessByRecordNumber(recordNumber);
                    Location loc = locations.get(recordNumber);
                    access.setLatitude(loc.getLatitude());
                    access.setLongitude(loc.getLongitude());
                    db.updatePublicAccess(access);
                    publishProgress(++progress);
                }
            }
            database.setTransactionSuccessful();
            return db.getPublicAccessesCount();
        } finally {
            database.endTransaction();
        }
    } catch (Exception e) {
        error = e;
        Log.e(TAG, "Error loading data: " + e.getLocalizedMessage(), e);
        return -1;
    }
}

From source file:com.zetaDevelopment.phonegap.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Executes a batch request and sends the results via sendJavascriptCB().
 *
 * @param dbname//from  www  .  j ava  2  s.  co  m
 *            The name of the database.
 *
 * @param queryarr
 *            Array of query strings
 *
 * @param jsonparams
 *            Array of JSON query parameters
 *
 * @param queryIDs
 *            Array of query ids
 *
 * @param tx_id
 *            Transaction id
 *
 */
private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonparams, String[] queryIDs,
        String tx_id) {
    SQLiteDatabase mydb = this.getDatabase(dbname);

    if (mydb == null)
        return;

    try {
        mydb.beginTransaction();

        String query = "";
        String query_id = "";
        int len = queryarr.length;

        for (int i = 0; i < len; i++) {
            query = queryarr[i];
            query_id = queryIDs[i];
            if (query.toLowerCase(Locale.getDefault()).startsWith("insert") && jsonparams != null) {
                SQLiteStatement myStatement = mydb.compileStatement(query);
                for (int j = 0; j < jsonparams[i].length(); j++) {
                    if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double) {
                        myStatement.bindDouble(j + 1, jsonparams[i].getDouble(j));
                    } else if (jsonparams[i].get(j) instanceof Number) {
                        myStatement.bindLong(j + 1, jsonparams[i].getLong(j));
                    } else {
                        myStatement.bindString(j + 1, jsonparams[i].getString(j));
                    }
                }
                long insertId = myStatement.executeInsert();

                String result = "{'insertId':'" + insertId + "'}";
                this.sendJavascriptCB("window.SQLitePluginTransactionCB.queryCompleteCallback('" + tx_id + "','"
                        + query_id + "', " + result + ");");
            } else {
                String[] params = null;

                if (jsonparams != null) {
                    params = new String[jsonparams[i].length()];

                    for (int j = 0; j < jsonparams[i].length(); j++) {
                        if (jsonparams[i].isNull(j))
                            params[j] = "";
                        else
                            params[j] = jsonparams[i].getString(j);
                    }
                }

                Cursor myCursor = mydb.rawQuery(query, params);

                if (query_id.length() > 0)
                    this.processResults(myCursor, query_id, tx_id);

                myCursor.close();
            }
        }
        mydb.setTransactionSuccessful();
    } catch (SQLiteException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } catch (JSONException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } finally {
        mydb.endTransaction();
        Log.v("executeSqlBatch", tx_id);
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txCompleteCallback('" + tx_id + "');");
    }
}

From source file:org.liberty.android.fantastischmemopro.DatabaseHelper.java

public static void createEmptyDatabase(String path, String name) throws IOException, SQLException {
    File dbfile = new File(path + "/" + name);
    if (dbfile.exists()) {
        // throw new IOException("DB already exist");
        /* Create a backup and overwrite  it instead poping up an error */
        File backupFile = new File(dbfile.getAbsolutePath().replaceAll(".db$", ".old.db"));
        if (backupFile.exists()) {
            backupFile.delete();/*from  w w w. j  ava  2 s .  c  o m*/
        }
        dbfile.renameTo(backupFile);
    }
    SQLiteDatabase database = SQLiteDatabase.openDatabase(path + "/" + name, null,
            SQLiteDatabase.OPEN_READWRITE | SQLiteDatabase.CREATE_IF_NECESSARY);

    database.execSQL(
            "CREATE TABLE dict_tbl(_id INTEGER PRIMARY KEY ASC AUTOINCREMENT, question TEXT, answer TEXT, note TEXT, category TEXT)");
    database.execSQL(
            "CREATE TABLE learn_tbl(_id INTEGER PRIMARY KEY ASC AUTOINCREMENT, date_learn, interval, grade INTEGER, easiness REAL, acq_reps INTEGER, ret_reps INTEGER, lapses INTEGER, acq_reps_since_lapse INTEGER, ret_reps_since_lapse INTEGER)");
    database.execSQL("CREATE TABLE control_tbl(ctrl_key TEXT, value TEXT)");

    database.beginTransaction();
    try {
        database.execSQL("DELETE FROM learn_tbl");
        database.execSQL("INSERT INTO learn_tbl(_id) SELECT _id FROM dict_tbl");
        database.execSQL(
                "UPDATE learn_tbl SET date_learn = '2010-01-01', interval = 0, grade = 0, easiness = 2.5, acq_reps = 0, ret_reps  = 0, lapses = 0, acq_reps_since_lapse = 0, ret_reps_since_lapse = 0");
        database.execSQL("INSERT INTO control_tbl(ctrl_key, value) VALUES('question_locale', 'US')");
        database.execSQL("INSERT INTO control_tbl(ctrl_key, value) VALUES('answer_locale', 'US')");
        database.execSQL("INSERT INTO control_tbl(ctrl_key, value) VALUES('question_align', 'center')");
        database.execSQL("INSERT INTO control_tbl(ctrl_key, value) VALUES('answer_align', 'center')");
        database.execSQL("INSERT INTO control_tbl(ctrl_key, value) VALUES('question_font_size', '24')");
        database.execSQL("INSERT INTO control_tbl(ctrl_key, value) VALUES('answer_font_size', '24')");
        database.setTransactionSuccessful();
    } finally {
        database.endTransaction();
        database.close();
    }

}

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

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

    db.beginTransaction();
    try {/*  w  w w  .  j a  v  a2s . co m*/
        // 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;
}