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:com.alchemiasoft.common.content.BookDBOpenHelper.java

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    try {/* w w w .  j  a  v  a  2 s  .c  om*/
        db.beginTransaction();

        db.execSQL(BookDB.Book.DELETE_TABLE);

        onCreate(db);

        db.setTransactionSuccessful();
        Log.i(TAG_LOG, "Successfully upgraded " + BookDB.NAME);
    } catch (Exception e) {
        Log.e(TAG_LOG, "Error creating " + BookDB.NAME + ": ", e);
    } finally {
        db.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  w w .  j ava2  s.  c  om
        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:net.willwebberley.gowertides.utils.WeatherDatabase.java

public Boolean insertAllData(String data) {
    JSONObject jsonArray = null;/*from w w w.  j a  v  a2  s  .c  o  m*/
    JSONArray weatherArray = null;
    JSONArray surfArray = null;

    try {
        jsonArray = new JSONObject(data);
        weatherArray = jsonArray.getJSONArray("weather");
        surfArray = jsonArray.getJSONArray("surf");
    } catch (Exception e) {
        System.err.println("couldn't parse JSON");
        return false;
    }

    SQLiteDatabase db = this.getWritableDatabase();
    int err_count = 0;

    /* Insert weather data */
    db.beginTransaction();
    Boolean weatherSuccess = insertWeatherData(weatherArray.toString(), db);
    if (!weatherSuccess) {
        err_count++;
        System.err.println("Error storing weather");
        db.endTransaction();
    } else {
        db.setTransactionSuccessful();
        db.endTransaction();
    }

    /* Insert surf data - using transactions to help performance */
    db.beginTransaction();
    Boolean surfSuccess = insertSurfData(surfArray.toString(), db);
    if (!surfSuccess) {
        err_count++;
        System.err.println("Error storing surf");
        db.endTransaction();
    } else {
        db.setTransactionSuccessful();
        db.endTransaction();
    }

    if (err_count > 0) {
        db.endTransaction();
        return false;
    }

    return true;
}

From source file:ru.ming13.gambit.database.DatabaseOperator.java

private void insertDatabaseContents(SQLiteDatabase database, File databaseFile) {
    database.execSQL(SqlBuilder.buildAttachingClause(databaseFile.getAbsolutePath(), DATABASE_ALIAS));

    try {/*from  w w w.j av  a2s.  c  o  m*/
        database.beginTransaction();

        database.execSQL(SqlBuilder.buildInsertionClause(DatabaseSchema.Tables.DECKS, DATABASE_ALIAS));
        database.execSQL(SqlBuilder.buildInsertionClause(DatabaseSchema.Tables.CARDS, DATABASE_ALIAS));

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

    database.execSQL(SqlBuilder.buildDetachingClause(DATABASE_ALIAS));
}

From source file:com.appsimobile.appsii.module.apps.AppsProvider.java

@Override
public int bulkInsert(Uri uri, @NonNull ContentValues[] values) {
    SqlArguments args = new SqlArguments(uri);

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    db.beginTransaction();//from   w  w w  .  java2  s  .  c o m
    try {
        int numValues = values.length;
        for (int i = 0; i < numValues; i++) {
            if (db.insert(args.table, null, values[i]) < 0)
                return 0;
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }

    sendNotify(uri);
    return values.length;
}

From source file:edu.htl3r.schoolplanner.backend.database.AutoSelectDatabase.java

@Override
public void setAutoSelect(AutoSelectSet autoSelectSet) {
    final String TABLE = DatabaseAutoSelectConstants.TABLE_AUTO_SELECT_NAME;

    SQLiteDatabase database = this.database.openDatabase(true);

    this.database.deleteAllRowsWithLoginSetKey(database, TABLE);

    ContentValues values = new ContentValues();
    values.put(DatabaseCreateConstants.TABLE_LOGINSET_KEY, this.database.getLoginSetKeyForTable());
    values.put(DatabaseAutoSelectConstants.ENABLED, autoSelectSet.isEnabled());
    values.put(DatabaseAutoSelectConstants.TYPE, autoSelectSet.getAutoSelectType());
    values.put(DatabaseAutoSelectConstants.VALUE, autoSelectSet.getAutoSelectValue());

    database.beginTransaction();/*from  w w  w  .j  a va  2 s.  co  m*/

    this.database.insert(database, TABLE, values);

    database.setTransactionSuccessful();
    database.endTransaction();
    this.database.closeDatabase(database);
}

From source file:nerd.tuxmobil.fahrplan.congress.FahrplanMisc.java

public static void addAlarm(Context context, Lecture lecture, int alarmTimesIndex) {
    int[] alarm_times = { 0, 5, 10, 15, 30, 45, 60 };
    long when;/*  w ww  . ja va2s  .  c  om*/
    Time time;
    long startTime;
    long startTimeInSeconds = lecture.dateUTC;

    if (startTimeInSeconds > 0) {
        when = startTimeInSeconds;
        startTime = startTimeInSeconds;
        time = new Time();
    } else {
        time = lecture.getTime();
        startTime = time.normalize(true);
        when = time.normalize(true);
    }
    long alarmTimeDiffInSeconds = alarm_times[alarmTimesIndex] * 60 * 1000;
    when -= alarmTimeDiffInSeconds;

    // DEBUG
    // when = System.currentTimeMillis() + (30 * 1000);

    time.set(when);
    MyApp.LogDebug("addAlarm", "Alarm time: " + time.format("%Y-%m-%dT%H:%M:%S%z") + ", in seconds: " + when);

    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra(BundleKeys.ALARM_LECTURE_ID, lecture.lecture_id);
    intent.putExtra(BundleKeys.ALARM_DAY, lecture.day);
    intent.putExtra(BundleKeys.ALARM_TITLE, lecture.title);
    intent.putExtra(BundleKeys.ALARM_START_TIME, startTime);
    intent.setAction(AlarmReceiver.ALARM_LECTURE);

    intent.setData(Uri.parse("alarm://" + lecture.lecture_id));

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingintent = PendingIntent.getBroadcast(context, Integer.parseInt(lecture.lecture_id),
            intent, 0);

    // Cancel any existing alarms for this lecture
    alarmManager.cancel(pendingintent);

    // Set new alarm
    alarmManager.set(AlarmManager.RTC_WAKEUP, when, pendingintent);

    int alarmTimeInMin = alarm_times[alarmTimesIndex];

    // write to DB

    AlarmsDBOpenHelper alarmDB = new AlarmsDBOpenHelper(context);

    SQLiteDatabase db = alarmDB.getWritableDatabase();

    // delete any previous alarms of this lecture
    try {
        db.beginTransaction();
        db.delete(AlarmsTable.NAME, AlarmsTable.Columns.EVENT_ID + "=?", new String[] { lecture.lecture_id });

        ContentValues values = new ContentValues();

        values.put(AlarmsTable.Columns.EVENT_ID, Integer.parseInt(lecture.lecture_id));
        values.put(AlarmsTable.Columns.EVENT_TITLE, lecture.title);
        values.put(AlarmsTable.Columns.ALARM_TIME_IN_MIN, alarmTimeInMin);
        values.put(AlarmsTable.Columns.TIME, when);
        DateFormat df = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT);
        values.put(AlarmsTable.Columns.TIME_TEXT, df.format(new Date(when)));
        values.put(AlarmsTable.Columns.DISPLAY_TIME, startTime);
        values.put(AlarmsTable.Columns.DAY, lecture.day);

        db.insert(AlarmsTable.NAME, null, values);
        db.setTransactionSuccessful();
    } catch (SQLException e) {
    } finally {
        db.endTransaction();
        db.close();
    }

    lecture.has_alarm = true;
}

From source file:au.org.ala.fielddata.mobile.dao.DatabaseHelper.java

@Override
public void onCreate(SQLiteDatabase db) {
    try {/*  w ww.j ava2  s . c  o  m*/
        db.beginTransaction();

        for (String table : TABLES) {
            db.execSQL("CREATE TABLE " + table + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, server_id INTEGER, "
                    + "created INTEGER, updated INTEGER, last_sync INTEGER" + "name TEXT, json TEXT)");

            createServerIdIndex(db, table);
        }

        createRecordTable(db);
        createSpeciesTables(db);
        createAttributeRowTable(db);

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

}

From source file:com.dm.wallpaper.board.databases.Database.java

public void addCategories(List<WallpaperJson> categories) {
    String query = "INSERT INTO " + TABLE_CATEGORIES + " (" + KEY_NAME + "," + KEY_THUMB_URL
            + ") VALUES (?,?);";
    SQLiteDatabase db = this.getWritableDatabase();
    SQLiteStatement statement = db.compileStatement(query);
    db.beginTransaction();/* ww w  .j  av  a 2s .  c  o m*/

    for (int i = 0; i < categories.size(); i++) {
        statement.clearBindings();
        statement.bindString(1, categories.get(i).name);
        statement.bindString(2, categories.get(i).thumbUrl == null ? "" : categories.get(i).thumbUrl);
        statement.execute();
    }
    db.setTransactionSuccessful();
    db.endTransaction();
    db.close();
}

From source file:syncthing.android.settings.AppSettings.java

public void setDefaultCredentials(Credentials creds) {
    SQLiteDatabase _db = db.getWritableDatabase();
    try {//from ww w  .  ja va 2s . com
        _db.beginTransaction();
        ContentValues cv = new ContentValues();
        cv.put(CredentialsDB.SCHEMA.DEFAULT, 0);
        //first unset default for everyone
        _db.update(CredentialsDB.SCHEMA.TABLE, cv, null, null);
        cv.put(CredentialsDB.SCHEMA.DEFAULT, 1);
        String[] sel = new String[] { creds.id };
        //set default for specified device
        _db.update(CredentialsDB.SCHEMA.TABLE, cv, credentialsDeviceIdSel, sel);
        _db.setTransactionSuccessful();
    } finally {
        _db.endTransaction();
    }
}