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:Main.java

private static void executeStatements(SQLiteDatabase database, List<String> statements) {
    try {/*from  w w  w  .j a  v  a  2 s  .  c  om*/
        database.beginTransaction();
        for (String statement : statements) {
            database.execSQL(statement);
        }
        database.setTransactionSuccessful();
    } finally {
        database.endTransaction();
    }
}

From source file:Main.java

public static int executeSqlStatementsInTx(SQLiteDatabase db, String[] statements) {
    db.beginTransaction();
    try {//from w w  w. j a va  2  s . c  o  m
        int count = executeSqlStatements(db, statements);
        db.setTransactionSuccessful();
        return count;
    } finally {
        db.endTransaction();
    }
}

From source file:Main.java

public static void beginTransactionNonExclusive(SQLiteDatabase db) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        db.beginTransactionNonExclusive();
    } else {//w ww.ja  v a 2 s  .com
        db.beginTransaction();
    }
}

From source file:com.contentful.vault.SqliteHelper.java

static void clearRecords(SpaceHelper helper, SQLiteDatabase db) {
    db.beginTransaction();
    try {/* ww w .  j a v a  2s  .  c o  m*/
        db.delete(escape(TABLE_ENTRY_TYPES), null, null);
        db.delete(escape(TABLE_SYNC_INFO), null, null);
        for (String code : helper.getLocales()) {
            db.delete(escape(localizeName(TABLE_ASSETS, code)), null, null);
            db.delete(escape(localizeName(TABLE_LINKS, code)), null, null);

            for (ModelHelper<?> modelHelper : helper.getModels().values()) {
                db.delete(escape(localizeName(modelHelper.getTableName(), code)), null, null);
            }
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}

From source file:curso.android.DAO.RespostaDAO.java

private static void createTable(SQLiteDatabase database, String tableName) {
    try {//from   w w w . j  a va  2  s .c  o m
        database.beginTransaction();

        String tableSql = "CREATE TABLE IF NOT EXISTS " + tableName + " ("
                + "asw_id INTEGER PRIMARY KEY AUTOINCREMENT," + "ask_id INTEGER," + "user_id INTEGER,"
                + "asw_resposta TEXT," + "user_name TEXT);";
        database.execSQL(tableSql);

        database.setTransactionSuccessful();
    } finally {
        database.endTransaction();
    }
}

From source file:org.thinschema.dataaccess.JSONAdapter.java

/**
 * Fill a table with data from a JSON. The JSON must contain an array of
 * JSON named 'rows', where each JSON represents one row (or record)
 * in the database./*from  ww w .j  a v a 2  s.  c  om*/
 *
 * @param sqLiteDatabase SQLiteDatabase instance.
 * @param dbSchema       Database schema.
 * @param tableName      Table name.
 * @param jsonData       JSONObject
 * @return true if insertion is successful.
 */
public static boolean fill(SQLiteDatabase sqLiteDatabase, DBSchema dbSchema, String tableName,
        JSONObject jsonData) {
    boolean success = true;
    JSONArray data = jsonData.optJSONArray("rows");

    sqLiteDatabase.beginTransaction();
    try {
        if (data != null && data.length() > 0) {
            for (int i = 0, size = data.length(); i < size; ++i) {
                JSONObject row = data.optJSONObject(i);
                ContentValues cv = toContentValues(row, dbSchema, tableName);
                if (sqLiteDatabase.insert(tableName, null, cv) == -1) {
                    success = false;
                    break;
                }
            }
        }

        if (success) {
            sqLiteDatabase.setTransactionSuccessful();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        sqLiteDatabase.endTransaction();
    }
    return success;
}

From source file:org.droidparts.inner.PersistUtils.java

public static <Result> Result executeInTransaction(SQLiteDatabase db, Callable<Result> task) {
    db.beginTransaction();
    try {/*from  w  ww  .  ja v a2  s  .com*/
        Result result = task.call();
        db.setTransactionSuccessful();
        return result;
    } catch (Exception e) {
        L.w(e.getMessage());
        L.d(e);
        return null;
    } finally {
        db.endTransaction();
    }
}

From source file:curso.android.DAO.PerguntaDAO.java

private static void createTable(SQLiteDatabase database, String tableName) {
    try {//w  ww .  ja  v a  2s  . com
        // begin the transaction
        database.beginTransaction();

        // Create a table
        String tableSql = "CREATE TABLE IF NOT EXISTS " + tableName + " (" + "ask_id INTEGER PRIMARY KEY,"
                + "user_id INTEGER," + "ask_pergunta TEXT," + "user_name TEXT," + "status INTEGER);";
        database.execSQL(tableSql);

        // this makes sure transaction is committed
        database.setTransactionSuccessful();
    } finally {
        database.endTransaction();
    }
}

From source file:com.xfinity.ceylon_steel.controller.CustomerController.java

public static void downloadCustomers(final Context context) {
    new AsyncTask<User, Void, JSONArray>() {

        @Override/*from   w ww . j  a  va  2s.  c  o  m*/
        protected void onPreExecute() {
            if (UserController.progressDialog == null) {
                UserController.progressDialog = new ProgressDialog(context);
                UserController.progressDialog.setMessage("Downloading Data");
                UserController.progressDialog.setCanceledOnTouchOutside(false);
            }
            if (!UserController.progressDialog.isShowing()) {
                UserController.progressDialog.show();
            }
        }

        @Override
        protected JSONArray doInBackground(User... users) {
            try {
                User user = users[0];
                HashMap<String, Object> parameters = new HashMap<String, Object>();
                parameters.put("userId", user.getUserId());
                return getJsonArray(getCustomersOfUser, parameters, context);
            } catch (IOException ex) {
                Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (JSONException ex) {
                Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
            }
            return null;
        }

        @Override
        protected void onPostExecute(JSONArray result) {
            if (UserController.atomicInteger.decrementAndGet() == 0 && UserController.progressDialog != null
                    && UserController.progressDialog.isShowing()) {
                UserController.progressDialog.dismiss();
                UserController.progressDialog = null;
            }
            if (result != null) {
                SQLiteDatabaseHelper databaseInstance = SQLiteDatabaseHelper.getDatabaseInstance(context);
                SQLiteDatabase database = databaseInstance.getWritableDatabase();
                SQLiteStatement compiledStatement = database
                        .compileStatement("replace into tbl_customer(customerId,customerName) values(?,?)");
                try {
                    database.beginTransaction();
                    for (int i = 0; i < result.length(); i++) {
                        JSONObject customer = result.getJSONObject(i);
                        compiledStatement.bindAllArgsAsStrings(
                                new String[] { Integer.toString(customer.getInt("customerId")),
                                        customer.getString("customerName") });
                        long response = compiledStatement.executeInsert();
                        if (response == -1) {
                            return;
                        }
                    }
                    database.setTransactionSuccessful();
                    Toast.makeText(context, "Customers downloaded successfully", Toast.LENGTH_SHORT).show();
                } catch (JSONException ex) {
                    Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
                    Toast.makeText(context, "Unable parse customers", Toast.LENGTH_SHORT).show();
                } finally {
                    database.endTransaction();
                    databaseInstance.close();
                }
            } else {
                Toast.makeText(context, "Unable to download customers", Toast.LENGTH_SHORT).show();
            }
        }

    }.execute(UserController.getAuthorizedUser(context));
}

From source file:org.opendatakit.common.android.database.DataModelDatabaseHelper.java

public static void deleteTableAndData(SQLiteDatabase db, String formId) {
    try {// w ww  . jav  a  2s.c  o m
        IdInstanceNameStruct ids = getIds(db, formId);

        String whereClause = TableDefinitionsColumns.TABLE_ID + " = ?";
        String[] whereArgs = { ids.tableId };

        db.beginTransaction();

        // Drop the table used for the formId
        db.execSQL("DROP TABLE IF EXISTS " + ids.tableId + ";");

        // Delete the table definition for the tableId
        int count = db.delete(TABLE_DEFS_TABLE_NAME, whereClause, whereArgs);

        // Delete the column definitions for this tableId
        db.delete(COLUMN_DEFINITIONS_TABLE_NAME, whereClause, whereArgs);

        // Delete the uploads for the tableId
        String uploadWhereClause = InstanceColumns.DATA_TABLE_TABLE_ID + " = ?";
        db.delete(UPLOADS_TABLE_NAME, uploadWhereClause, whereArgs);

        // Delete the values from the 4 key value stores
        db.delete(KEY_VALUE_STORE_DEFAULT_TABLE_NAME, whereClause, whereArgs);
        db.delete(KEY_VALUE_STORE_ACTIVE_TABLE_NAME, whereClause, whereArgs);
        db.delete(KEY_VALUE_STORE_SERVER_TABLE_NAME, whereClause, whereArgs);
        db.delete(KEY_VALULE_STORE_SYNC_TABLE_NAME, whereClause, whereArgs);

        db.setTransactionSuccessful();

    } catch (Exception ex) {
        Log.e(t, "Exception during deletion of data for formId:" + formId + " exception: " + ex.toString());
    } finally {
        db.endTransaction();
    }
}