List of usage examples for android.database.sqlite SQLiteDatabase beginTransaction
public void beginTransaction()
From source file:ru.orangesoftware.financisto2.db.DatabaseAdapter.java
public int deleteAccount(long id) { SQLiteDatabase db = db(); db.beginTransaction(); try {/*from ww w . j av a 2s . c om*/ String[] sid = new String[] { String.valueOf(id) }; Account a = load(Account.class, id); writeDeleteLog(TRANSACTION_TABLE, a.remoteKey); db.execSQL(UPDATE_ORPHAN_TRANSACTIONS_1, sid); db.execSQL(UPDATE_ORPHAN_TRANSACTIONS_2, sid); db.delete(TRANSACTION_ATTRIBUTE_TABLE, TransactionAttributeColumns.TRANSACTION_ID + " in (SELECT _id from " + TRANSACTION_TABLE + " where " + TransactionColumns.from_account_id + "=?)", sid); db.delete(TRANSACTION_TABLE, TransactionColumns.from_account_id + "=?", sid); int count = db.delete(ACCOUNT_TABLE, "_id=?", sid); db.setTransactionSuccessful(); return count; } finally { db.endTransaction(); } }
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(); try {/* w w w . j ava2 s. co m*/ 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:ru.orangesoftware.financisto2.db.DatabaseAdapter.java
public long[] storeMissedSchedules(List<RestoredTransaction> restored, long now) { SQLiteDatabase db = db(); db.beginTransaction(); try {/*from ww w . jav a2 s .c om*/ int count = restored.size(); long[] restoredIds = new long[count]; HashMap<Long, Transaction> transactions = new HashMap<Long, Transaction>(); for (int i = 0; i < count; i++) { RestoredTransaction rt = restored.get(i); long transactionId = rt.transactionId; Transaction t = transactions.get(transactionId); if (t == null) { t = getTransaction(transactionId); transactions.put(transactionId, t); } t.id = -1; t.dateTime = rt.dateTime.getTime(); t.status = TransactionStatus.RS; t.isTemplate = 0; restoredIds[i] = insertOrUpdate(t); t.id = transactionId; } for (Transaction t : transactions.values()) { db.execSQL(UPDATE_LAST_RECURRENCE, new Object[] { now, t.id }); } db.setTransactionSuccessful(); return restoredIds; } finally { db.endTransaction(); } }
From source file:ru.orangesoftware.financisto2.db.DatabaseAdapter.java
/** * Re-populates running_balance for specific account * * @param account selected account/* w w w .j av a2s.c o m*/ */ public void rebuildRunningBalanceForAccount(Account account) { SQLiteDatabase db = db(); db.beginTransaction(); try { String accountId = String.valueOf(account.getId()); db.execSQL("delete from running_balance where account_id=?", new Object[] { accountId }); WhereFilter filter = new WhereFilter(""); filter.put(Criteria.eq(BlotterFilter.FROM_ACCOUNT_ID, accountId)); filter.asc("datetime"); filter.asc("_id"); Cursor c = getBlotterForAccountWithSplits(filter); Object[] values = new Object[4]; values[0] = accountId; try { long balance = 0; while (c.moveToNext()) { long parentId = c.getLong(BlotterColumns.parent_id.ordinal()); int isTransfer = c.getInt(BlotterColumns.is_transfer.ordinal()); if (parentId > 0) { if (isTransfer >= 0) { // we only interested in the second part of the transfer-split // which is marked with is_transfer=-1 (see v_blotter_for_account_with_splits) continue; } } long fromAccountId = c.getLong(BlotterColumns.from_account_id.ordinal()); long toAccountId = c.getLong(BlotterColumns.to_account_id.ordinal()); if (toAccountId > 0 && toAccountId == fromAccountId) { // weird bug when a transfer is done from an account to the same account continue; } balance += c.getLong(DatabaseHelper.BlotterColumns.from_amount.ordinal()); values[1] = c.getString(DatabaseHelper.BlotterColumns._id.ordinal()); values[2] = c.getString(DatabaseHelper.BlotterColumns.datetime.ordinal()); values[3] = balance; db.execSQL( "insert into running_balance(account_id,transaction_id,datetime,balance) values (?,?,?,?)", values); } } finally { c.close(); } updateAccountLastTransactionDate(account.id); db.setTransactionSuccessful(); } finally { db.endTransaction(); } }
From source file:ru.orangesoftware.financisto2.db.DatabaseAdapter.java
private long duplicateTransaction(long id, int isTemplate, int multiplier) { SQLiteDatabase db = db(); db.beginTransaction(); try {//from ww w . j a va 2 s . c o m long now = System.currentTimeMillis(); Transaction transaction = getTransaction(id); if (transaction.isSplitChild()) { id = transaction.parentId; transaction = getTransaction(id); } transaction.lastRecurrence = now; updateTransaction(transaction); transaction.id = -1; transaction.isTemplate = isTemplate; transaction.dateTime = now; transaction.remoteKey = null; if (isTemplate == 0) { transaction.recurrence = null; transaction.notificationOptions = null; } if (multiplier > 1) { transaction.fromAmount *= multiplier; transaction.toAmount *= multiplier; } long transactionId = insertTransaction(transaction); Map<Long, String> attributesMap = getAllAttributesForTransaction(id); LinkedList<TransactionAttribute> attributes = new LinkedList<TransactionAttribute>(); for (long attributeId : attributesMap.keySet()) { TransactionAttribute ta = new TransactionAttribute(); ta.attributeId = attributeId; ta.value = attributesMap.get(attributeId); attributes.add(ta); } if (attributes.size() > 0) { insertAttributes(transactionId, attributes); } List<Transaction> splits = getSplitsForTransaction(id); if (multiplier > 1) { for (Transaction split : splits) { split.fromAmount *= multiplier; split.remoteKey = null; } } transaction.id = transactionId; transaction.splits = splits; insertSplits(transaction); db.setTransactionSuccessful(); return transactionId; } finally { db.endTransaction(); } }
From source file:pl.selvin.android.syncframework.content.BaseContentProvider.java
protected boolean Sync(String service, String scope, String params) { final Date start = new Date(); boolean hasError = false; if (params == null) params = ""; final SQLiteDatabase db = mDB.getWritableDatabase(); final ArrayList<TableInfo> notifyTableInfo = new ArrayList<TableInfo>(); final String download = String.format(contentHelper.DOWNLOAD_SERVICE_URI, service, scope, params); final String upload = String.format(contentHelper.UPLOAD_SERVICE_URI, service, scope, params); final String scopeServerBlob = String.format("%s.%s.%s", service, scope, _.serverBlob); String serverBlob = null;//from w w w . j av a 2 s.c om Cursor cur = db.query(BlobsTable.NAME, new String[] { BlobsTable.C_VALUE }, BlobsTable.C_NAME + "=?", new String[] { scopeServerBlob }, null, null, null); final String originalBlob; if (cur.moveToFirst()) { originalBlob = serverBlob = cur.getString(0); } else { originalBlob = null; } cur.close(); db.beginTransaction(); try { boolean nochanges = false; if (serverBlob != null) { nochanges = !contentHelper.hasDirtTable(db, scope); } boolean resolve = false; final Metadata meta = new Metadata(); final HashMap<String, Object> vals = new HashMap<String, Object>(); final ContentValues cv = new ContentValues(2); JsonFactory jsonFactory = new JsonFactory(); JsonToken current = null; String name = null; boolean moreChanges = false; boolean forceMoreChanges = false; do { final int requestMethod; final String serviceRequestUrl; final ContentProducer contentProducer; if (serverBlob != null) { requestMethod = HTTP_POST; if (nochanges) { serviceRequestUrl = download; } else { serviceRequestUrl = upload; forceMoreChanges = true; } contentProducer = new SyncContentProducer(jsonFactory, db, scope, serverBlob, !nochanges, notifyTableInfo, contentHelper); nochanges = true; } else { requestMethod = HTTP_GET; serviceRequestUrl = download; contentProducer = null; } if (moreChanges) { db.beginTransaction(); } Result result = executeRequest(requestMethod, serviceRequestUrl, contentProducer); if (result.getStatus() == HttpStatus.SC_OK) { final JsonParser jp = jsonFactory.createParser(result.getInputStream()); jp.nextToken(); // skip ("START_OBJECT(d) expected"); jp.nextToken(); // skip ("FIELD_NAME(d) expected"); if (jp.nextToken() != JsonToken.START_OBJECT) throw new Exception("START_OBJECT(d - object) expected"); while (jp.nextToken() != JsonToken.END_OBJECT) { name = jp.getCurrentName(); if (_.__sync.equals(name)) { current = jp.nextToken(); while (jp.nextToken() != JsonToken.END_OBJECT) { name = jp.getCurrentName(); current = jp.nextToken(); if (_.serverBlob.equals(name)) { serverBlob = jp.getText(); } else if (_.moreChangesAvailable.equals(name)) { moreChanges = jp.getBooleanValue() || forceMoreChanges; forceMoreChanges = false; } else if (_.resolveConflicts.equals(name)) { resolve = jp.getBooleanValue(); } } } else if (_.results.equals(name)) { if (jp.nextToken() != JsonToken.START_ARRAY) throw new Exception("START_ARRAY(results) expected"); while (jp.nextToken() != JsonToken.END_ARRAY) { meta.isDeleted = false; meta.tempId = null; vals.clear(); while (jp.nextToken() != JsonToken.END_OBJECT) { name = jp.getCurrentName(); current = jp.nextToken(); if (current == JsonToken.VALUE_STRING) { vals.put(name, jp.getText()); } else if (current == JsonToken.VALUE_NUMBER_INT) { vals.put(name, jp.getLongValue()); } else if (current == JsonToken.VALUE_NUMBER_FLOAT) { vals.put(name, jp.getDoubleValue()); } else if (current == JsonToken.VALUE_FALSE) { vals.put(name, 0L); } else if (current == JsonToken.VALUE_TRUE) { vals.put(name, 1L); } else if (current == JsonToken.VALUE_NULL) { vals.put(name, null); } else { if (current == JsonToken.START_OBJECT) { if (_.__metadata.equals(name)) { while (jp.nextToken() != JsonToken.END_OBJECT) { name = jp.getCurrentName(); jp.nextToken(); if (_.uri.equals(name)) { meta.uri = jp.getText(); } else if (_.type.equals(name)) { meta.type = jp.getText(); } else if (_.isDeleted.equals(name)) { meta.isDeleted = jp.getBooleanValue(); } else if (_.tempId.equals(name)) { meta.tempId = jp.getText(); } } } else if (_.__syncConflict.equals(name)) { while (jp.nextToken() != JsonToken.END_OBJECT) { name = jp.getCurrentName(); jp.nextToken(); if (_.isResolved.equals(name)) { } else if (_.conflictResolution.equals(name)) { } else if (_.conflictingChange.equals(name)) { while (jp.nextToken() != JsonToken.END_OBJECT) { name = jp.getCurrentName(); current = jp.nextToken(); if (current == JsonToken.START_OBJECT) { if (_.__metadata.equals(name)) { while (jp.nextToken() != JsonToken.END_OBJECT) { } } } } } } // resolve conf } else if (_.__syncError.equals(name)) { while (jp.nextToken() != JsonToken.END_OBJECT) { name = jp.getCurrentName(); jp.nextToken(); } } } } } TableInfo tab = contentHelper.getTableFromType(meta.type); if (meta.isDeleted) { tab.DeleteWithUri(meta.uri, db); } else { tab.SyncJSON(vals, meta, db); } if (!notifyTableInfo.contains(tab)) notifyTableInfo.add(tab); } } } jp.close(); if (!hasError) { cv.clear(); cv.put(BlobsTable.C_NAME, scopeServerBlob); cv.put(BlobsTable.C_VALUE, serverBlob); cv.put(BlobsTable.C_DATE, Calendar.getInstance().getTimeInMillis()); cv.put(BlobsTable.C_STATE, 0); db.replace(BlobsTable.NAME, null, cv); db.setTransactionSuccessful(); db.endTransaction(); if (DEBUG) { Log.d(TAG, "CP-Sync: commit changes"); } final ContentResolver cr = getContext().getContentResolver(); for (TableInfo t : notifyTableInfo) { final Uri nu = contentHelper.getDirUri(t.name, false); cr.notifyChange(nu, null, false); // false - do not force sync cause we are in sync if (DEBUG) { Log.d(TAG, "CP-Sync: notifyChange table: " + t.name + ", uri: " + nu); } for (String n : t.notifyUris) { cr.notifyChange(Uri.parse(n), null, false); if (DEBUG) { Log.d(TAG, "+uri: " + n); } } } notifyTableInfo.clear(); } } else { if (DEBUG) { Log.e(TAG, "Server error in fetching remote contacts: " + result.getStatus()); } hasError = true; break; } } while (moreChanges); } catch (final ConnectTimeoutException e) { hasError = true; if (DEBUG) { Log.e(TAG, "ConnectTimeoutException", e); } } catch (final IOException e) { hasError = true; if (DEBUG) { Log.e(TAG, Log.getStackTraceString(e)); } } catch (final ParseException e) { hasError = true; if (DEBUG) { Log.e(TAG, "ParseException", e); } } catch (final Exception e) { hasError = true; if (DEBUG) { Log.e(TAG, "ParseException", e); } } if (hasError) { db.endTransaction(); ContentValues cv = new ContentValues(); cv.put(BlobsTable.C_NAME, scopeServerBlob); cv.put(BlobsTable.C_VALUE, originalBlob); cv.put(BlobsTable.C_DATE, Calendar.getInstance().getTimeInMillis()); cv.put(BlobsTable.C_STATE, -1); db.replace(BlobsTable.NAME, null, cv); } /*-if (!hasError) { final ContentValues cv = new ContentValues(2); cv.put(BlobsTable.C_NAME, scopeServerBlob); cv.put(BlobsTable.C_VALUE, serverBlob); db.replace(BlobsTable.NAME, null, cv); db.setTransactionSuccessful(); } db.endTransaction(); if (!hasError) { for (String t : notifyTableInfo) { getContext().getContentResolver().notifyChange(getDirUri(t), null); } }*/ if (DEBUG) { Helpers.LogInfo(start); } return !hasError; }
From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java
@Override public void onCreate(SQLiteDatabase db) { db.beginTransaction(); createTable(db, MyInfo.TABLE, null, MyInfo._ID, "INTEGER PRIMARY KEY", MyInfo.PUBLIC_KEY, "TEXT", MyInfo.PRIVATE_KEY, "TEXT", MyInfo.NAME, "TEXT", MyInfo.EMAIL, "TEXT", MyInfo.PICTURE, "BLOB", MyInfo.ABOUT, "TEXT DEFAULT ''"); createTable(db, DbObject.TABLE, null, DbObject._ID, "INTEGER PRIMARY KEY", DbObject.TYPE, "TEXT", DbObject.SEQUENCE_ID, "INTEGER", DbObject.FEED_NAME, "TEXT", DbObject.APP_ID, "TEXT", DbObject.CONTACT_ID, "INTEGER", DbObject.DESTINATION, "TEXT", DbObject.JSON, "TEXT", DbObject.TIMESTAMP, "INTEGER", DbObject.LAST_MODIFIED_TIMESTAMP, "INTEGER", DbObject.SENT, "INTEGER DEFAULT 0", DbObject.DELETED, "INTEGER DEFAULT 0", DbObject.HASH, "INTEGER", DbObject.ENCODED, "BLOB", DbObject.CHILD_FEED_NAME, "TEXT", DbObject.RAW, "BLOB", DbObject.KEY_INT, "INTEGER"); db.execSQL("CREATE INDEX objects_by_sequence_id ON " + DbObject.TABLE + "(" + DbObject.CONTACT_ID + ", " + DbObject.FEED_NAME + ", " + DbObject.SEQUENCE_ID + ")"); createIndex(db, "INDEX", "objects_by_feed_name", DbObject.TABLE, DbObject.FEED_NAME); db.execSQL("CREATE INDEX objects_by_creator_id ON " + DbObject.TABLE + "(" + DbObject.CONTACT_ID + ", " + DbObject.SENT + ")"); createIndex(db, "INDEX", "child_feeds", DbObject.TABLE, DbObject.CHILD_FEED_NAME); createIndex(db, "INDEX", "objects_by_hash", DbObject.TABLE, DbObject.HASH); createIndex(db, "INDEX", "objects_by_int_key", DbObject.TABLE, DbObject.KEY_INT); createIndex(db, "INDEX", "objects_last_modified", DbObject.TABLE, DbObject.LAST_MODIFIED_TIMESTAMP); createTable(db, Contact.TABLE, null, Contact._ID, "INTEGER PRIMARY KEY", Contact.NAME, "TEXT", Contact.PUBLIC_KEY, "TEXT", Contact.PUBLIC_KEY_HASH_64, "INTEGER", Contact.SHARED_SECRET, "BLOB", Contact.PERSON_ID, "TEXT", Contact.EMAIL, "TEXT", Contact.PRESENCE, "INTEGER DEFAULT " + Presence.AVAILABLE, Contact.LAST_PRESENCE_TIME, "INTEGER DEFAULT 0", Contact.LAST_OBJECT_ID, "INTEGER", Contact.LAST_UPDATED, "INTEGER", Contact.NUM_UNREAD, "INTEGER DEFAULT 0", Contact.NEARBY, "INTEGER DEFAULT 0", Contact.STATUS, "TEXT", Contact.PICTURE, "BLOB", Contact.HIDDEN, "INTEGER DEFAULT 0"); createIndex(db, "UNIQUE INDEX", "contacts_by_person_id", Contact.TABLE, Contact.PERSON_ID); createIndex(db, "INDEX", "contacts_by_pkp", Contact.TABLE, Contact.PUBLIC_KEY_HASH_64); createTable(db, Subscriber.TABLE, new String[] { Subscriber.CONTACT_ID, Subscriber.FEED_NAME }, Subscriber._ID, "INTEGER PRIMARY KEY", Subscriber.CONTACT_ID, "INTEGER REFERENCES " + Contact.TABLE + "(" + Contact._ID + ") ON DELETE CASCADE", Subscriber.FEED_NAME, "TEXT"); createIndex(db, "INDEX", "subscribers_by_contact_id", Subscriber.TABLE, Subscriber.CONTACT_ID); createGroupBaseTable(db);/* w w w .j a va2 s.co m*/ createGroupMemberBaseTable(db); createRelationBaseTable(db); addRelationIndexes(db); createUserAttributesTable(db); generateAndStorePersonalInfo(db); db.setVersion(VERSION); db.setTransactionSuccessful(); db.endTransaction(); this.onOpen(db); //} }
From source file:org.pixmob.freemobile.netstat.SyncService.java
private void run(Intent intent, final SQLiteDatabase db) throws Exception { final long now = dateAtMidnight(System.currentTimeMillis()); Log.i(TAG, "Initializing statistics before uploading"); final LongSparseArray<DailyStat> stats = new LongSparseArray<DailyStat>(15); final Set<Long> uploadedStats = new HashSet<Long>(15); final long statTimestampStart = now - 7 * DAY_IN_MILLISECONDS; // Get pending uploads. Cursor c = db.query("daily_stat", new String[] { "stat_timestamp", "orange", "free_mobile", "sync" }, "stat_timestamp>=? AND stat_timestamp<?", new String[] { String.valueOf(statTimestampStart), String.valueOf(now) }, null, null, null); try {// ww w .java 2s. co m while (c.moveToNext()) { final long d = c.getLong(0); final int sync = c.getInt(3); if (SYNC_UPLOADED == sync) { uploadedStats.add(d); } else if (SYNC_PENDING == sync) { final DailyStat s = new DailyStat(); s.orange = c.getInt(1); s.freeMobile = c.getInt(2); stats.put(d, s); } } } finally { c.close(); } // Compute missing uploads. final ContentValues cv = new ContentValues(); db.beginTransaction(); try { for (long d = statTimestampStart; d < now; d += DAY_IN_MILLISECONDS) { if (stats.get(d) == null && !uploadedStats.contains(d)) { final DailyStat s = computeDailyStat(d); cv.put("stat_timestamp", d); cv.put("orange", s.orange); cv.put("free_mobile", s.freeMobile); cv.put("sync", SYNC_PENDING); db.insertOrThrow("daily_stat", null, cv); stats.put(d, s); } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } // Delete old statistics. if (DEBUG) { Log.d(TAG, "Cleaning up upload database"); } db.delete("daily_stat", "stat_timestamp<?", new String[] { String.valueOf(statTimestampStart) }); // Check if there are any statistics to upload. final int statsLen = stats.size(); if (statsLen == 0) { Log.i(TAG, "Nothing to upload"); return; } // Check if the remote server is up. final HttpClient client = createHttpClient(); try { client.head(createServerUrl(null)).execute(); } catch (HttpClientException e) { Log.w(TAG, "Remote server is not available: cannot upload statistics", e); return; } // Upload statistics. Log.i(TAG, "Uploading statistics"); final JSONObject json = new JSONObject(); final String deviceId = getDeviceId(); final boolean deviceWasRegistered = intent.getBooleanExtra(EXTRA_DEVICE_REG, false); for (int i = 0; i < statsLen; ++i) { final long d = stats.keyAt(i); final DailyStat s = stats.get(d); try { json.put("timeOnOrange", s.orange); json.put("timeOnFreeMobile", s.freeMobile); } catch (JSONException e) { final IOException ioe = new IOException("Failed to prepare statistics upload"); ioe.initCause(e); throw ioe; } final String url = createServerUrl( "/device/" + deviceId + "/daily/" + DateFormat.format("yyyyMMdd", d)); if (DEBUG) { Log.d(TAG, "Uploading statistics for " + DateUtils.formatDate(d) + " to: " + url); } final byte[] rawJson = json.toString().getBytes("UTF-8"); try { client.post(url).content(rawJson, "application/json") .expect(HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_NOT_FOUND) .to(new HttpResponseHandler() { @Override public void onResponse(HttpResponse response) throws Exception { final int sc = response.getStatusCode(); if (HttpURLConnection.HTTP_NOT_FOUND == sc) { // Check if the device has just been // registered. if (deviceWasRegistered) { throw new IOException("Failed to upload statistics"); } else { // Got 404: the device does not exist. // We need to register this device. registerDevice(deviceId); // Restart this service. startService(new Intent(getApplicationContext(), SyncService.class) .putExtra(EXTRA_DEVICE_REG, true)); } } else if (HttpURLConnection.HTTP_OK == sc) { // Update upload database. cv.clear(); cv.put("sync", SYNC_UPLOADED); db.update("daily_stat", cv, "stat_timestamp=?", new String[] { String.valueOf(d) }); if (DEBUG) { Log.d(TAG, "Upload done for " + DateUtils.formatDate(d)); } } } }).execute(); } catch (HttpClientException e) { final IOException ioe = new IOException("Failed to send request with statistics"); ioe.initCause(e); throw ioe; } } }
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 w w. j a v a 2 s.com * @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.ttrssreader.controllers.DBHelper.java
void insertCategories(Set<Category> set) { if (!isDBAvailable() || set == null) return;/*www . ja v a 2 s . c o m*/ 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); } }