List of usage examples for android.database.sqlite SQLiteDatabase beginTransaction
public void beginTransaction()
From source file:it.bradipao.berengar.DbTool.java
public static int json2table(SQLiteDatabase mDB, JSONObject jsonTable) { // vars//from w w w . java 2 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.concentricsky.android.khanacademy.data.remote.LibraryUpdaterTask.java
@Override protected Integer doInBackground(Void... params) { SharedPreferences prefs = dataService.getSharedPreferences(SETTINGS_NAME, Context.MODE_PRIVATE); // Connectivity receiver. final NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo(); ComponentName receiver = new ComponentName(dataService, WifiReceiver.class); PackageManager pm = dataService.getPackageManager(); if (activeNetwork == null || !activeNetwork.isConnected()) { // We've missed a scheduled update. Enable the receiver so it can launch an update when we reconnect. Log.d(LOG_TAG, "Missed library update: not connected. Enabling connectivity receiver."); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); return RESULT_CODE_FAILURE; } else {/*from w w w . jav a2 s.c om*/ // We are connected. Disable the receiver. Log.d(LOG_TAG, "Library updater connected. Disabling connectivity receiver."); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); } InputStream in = null; String etag = prefs.getString(SETTING_LIBRARY_ETAG, null); try { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); if (etag != null && !force) { conn.setRequestProperty("If-None-Match", etag); } int code = conn.getResponseCode(); switch (code) { case HttpStatus.SC_NOT_MODIFIED: // If we got a 304, we're done. // Use failure code to indicate there is no temp db to copy over. Log.d(LOG_TAG, "304 in library response."); return RESULT_CODE_FAILURE; default: // Odd, but on 1/3/13 I received correct json responses with a -1 for responseCode. Fall through. Log.w(LOG_TAG, "Error code in library response: " + code); case HttpStatus.SC_OK: // Parse response. in = conn.getInputStream(); JsonFactory factory = new JsonFactory(); final JsonParser parser = factory.createJsonParser(in); SQLiteDatabase tempDb = tempDbHelper.getWritableDatabase(); tempDb.beginTransaction(); try { tempDb.execSQL("delete from topic"); tempDb.execSQL("delete from topicvideo"); tempDb.execSQL("delete from video"); parseObject(parser, tempDb, null, 0); tempDb.setTransactionSuccessful(); } catch (Exception e) { e.printStackTrace(); return RESULT_CODE_FAILURE; } finally { tempDb.endTransaction(); tempDb.close(); } // Save etag once we've successfully parsed the response. etag = conn.getHeaderField("ETag"); prefs.edit().putString(SETTING_LIBRARY_ETAG, etag).apply(); // Move this new content from the temp db into the main one. mergeDbs(); return RESULT_CODE_SUCCESS; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (JsonParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { tempDbHelper.close(); } return RESULT_CODE_FAILURE; }
From source file:ru.orangesoftware.financisto2.db.MyEntityManager.java
public void deleteProject(long id) { SQLiteDatabase db = db(); db.beginTransaction(); try {/*from www . j ava2 s.c o m*/ delete(Project.class, id); ContentValues values = new ContentValues(); values.put("project_id", 0); db.update("transactions", values, "project_id=?", new String[] { String.valueOf(id) }); db.setTransactionSuccessful(); } finally { db.endTransaction(); } }
From source file:ru.orangesoftware.financisto2.db.MyEntityManager.java
public long saveOrUpdate(Currency currency) { SQLiteDatabase db = db(); db.beginTransaction(); try {//from w ww. j a va 2 s . c o m if (currency.isDefault) { db.execSQL(UPDATE_DEFAULT_FLAG); } long id = super.saveOrUpdate(currency); db.setTransactionSuccessful(); return id; } finally { db.endTransaction(); } }
From source file:com.wheelermarine.android.publicAccesses.Updater.java
@Override protected Integer doInBackground(URL... urls) { try {/*from www. 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").startsWith("ftp://ftp.dnr.state.mn.us")) { 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); } }); FTPClient ftp = new FTPClient(); try { ftp.setConnectTimeout(timeout * 1000); ftp.setDefaultTimeout(timeout * 1000); ftp.connect(dataURL.getHost()); ftp.enterLocalPassiveMode(); // After connection attempt, you should check the reply code // to verify success. if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { ftp.disconnect(); throw new IOException("FTP server refused connection: " + ftp.getReplyString()); } // Login using the standard anonymous credentials. if (!ftp.login("anonymous", "anonymous")) { ftp.disconnect(); throw new IOException("FTP Error: " + ftp.getReplyString()); } Map<Integer, Location> locations = null; // Download the ZIP archive. Log.v(TAG, "Downloading: " + dataURL.getFile()); ftp.setFileType(FTP.BINARY_FILE_TYPE); InputStream in = ftp.retrieveFileStream(dataURL.getFile()); 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); } } } finally { if (ftp.isConnected()) ftp.disconnect(); } 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:ru.orangesoftware.financisto2.db.MyEntityManager.java
public void deleteAttribute(long id) { SQLiteDatabase db = db(); db.beginTransaction(); try {// ww w. ja v a2s . com Attribute attr = get(Attribute.class, id); String key = attr.remoteKey; String[] p = new String[] { String.valueOf(id) }; db.delete(ATTRIBUTES_TABLE, DatabaseHelper.AttributeColumns.ID + "=?", p); db.delete(CATEGORY_ATTRIBUTE_TABLE, DatabaseHelper.CategoryAttributeColumns.ATTRIBUTE_ID + "=?", p); db.delete(TRANSACTION_ATTRIBUTE_TABLE, DatabaseHelper.TransactionAttributeColumns.ATTRIBUTE_ID + "=?", p); db.setTransactionSuccessful(); writeDeleteLog(ATTRIBUTES_TABLE, key); } finally { db.endTransaction(); } }
From source file:ru.orangesoftware.financisto2.db.MyEntityManager.java
public long insertBudget(Budget budget) { SQLiteDatabase db = db(); db.beginTransaction(); try {//from ww w . j a v a 2s.c om if (budget.id > 0) { deleteBudget(budget.id); } long id = 0; Recur recur = RecurUtils.createFromExtraString(budget.recur); Period[] periods = RecurUtils.periods(recur); for (int i = 0; i < periods.length; i++) { Period p = periods[i]; budget.id = -1; budget.parentBudgetId = id; budget.recurNum = i; budget.startDate = p.start; budget.endDate = p.end; long bid = super.saveOrUpdate(budget); if (i == 0) { id = bid; } } db.setTransactionSuccessful(); return id; } finally { db.endTransaction(); } }
From source file:com.google.android.apps.santatracker.service.APIProcessor.java
private int processRoute(JSONArray json) { SQLiteDatabase db = mDestinationDBHelper.getWritableDatabase(); db.beginTransaction(); try {/* w w w. jav a 2 s . c o m*/ // loop over each destination long previousPresents = mPreferences.getTotalPresents(); int i; for (i = 0; i < json.length(); i++) { JSONObject dest = json.getJSONObject(i); JSONObject location = dest.getJSONObject(FIELD_DETAILS_LOCATION); long presentsTotal = dest.getLong(FIELD_DETAILS_PRESENTSDELIVERED); long presents = presentsTotal - previousPresents; previousPresents = presentsTotal; // Name String city = dest.getString(FIELD_DETAILS_CITY); String region = null; String country = null; if (dest.has(FIELD_DETAILS_REGION)) { region = dest.getString(FIELD_DETAILS_REGION); if (region.length() < 1) { region = null; } } if (dest.has(FIELD_DETAILS_COUNTRY)) { country = dest.getString(FIELD_DETAILS_COUNTRY); if (country.length() < 1) { country = null; } } // if (mDebugLog) { // Log.d(TAG, "Location: " + city); // } // Detail fields JSONObject details = dest.getJSONObject(FIELD_DETAILS_DETAILS); long timezone = details.isNull(FIELD_DETAILS_TIMEZONE) ? 0L : details.getLong(FIELD_DETAILS_TIMEZONE); long altitude = details.getLong(FIELD_DETAILS_ALTITUDE); String photos = details.has(FIELD_DETAILS_PHOTOS) ? details.getString(FIELD_DETAILS_PHOTOS) : EMPTY_STRING; String weather = details.has(FIELD_DETAILS_WEATHER) ? details.getString(FIELD_DETAILS_WEATHER) : EMPTY_STRING; String streetview = details.has(FIELD_DETAILS_STREETVIEW) ? details.getString(FIELD_DETAILS_STREETVIEW) : EMPTY_STRING; String gmmStreetview = details.has(FIELD_DETAILS_GMMSTREETVIEW) ? details.getString(FIELD_DETAILS_GMMSTREETVIEW) : EMPTY_STRING; try { // All parsed, insert into DB mDestinationDBHelper.insertDestination(db, dest.getString(FIELD_IDENTIFIER), dest.getLong(FIELD_ARRIVAL), dest.getLong(FIELD_DEPARTURE), city, region, country, location.getDouble(FIELD_DETAILS_LOCATION_LAT), location.getDouble(FIELD_DETAILS_LOCATION_LNG), presentsTotal, presents, timezone, altitude, photos, weather, streetview, gmmStreetview); } catch (android.database.sqlite.SQLiteConstraintException e) { // ignore duplicate locations } } db.setTransactionSuccessful(); // Update mPreferences mPreferences.setDBTimestamp(System.currentTimeMillis()); mPreferences.setTotalPresents(previousPresents); return i; } catch (JSONException e) { Log.d(TAG, "Santa location tracking error 30"); SantaLog.d(TAG, "JSON Exception", e); } finally { db.endTransaction(); } return 0; }
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(); this.database.insert(database, TABLE, values); database.setTransactionSuccessful(); database.endTransaction();/*ww w. jav a 2 s.c o m*/ this.database.closeDatabase(database); }
From source file:org.devtcg.five.provider.FiveSyncAdapter.java
@Override public void getServerDiffs(SyncContext context, AbstractSyncProvider serverDiffs) { if (mSource != ((FiveProvider) serverDiffs).mSource) throw new IllegalStateException("What the hell happened here?"); context.moreRecordsToGet = true;// w w w . j a v a2 s . co m /* Source must have been deleted or something? */ if (mSource.moveToFirst() == false) return; AuthHelper.setCredentials(sClient, mSource); long modifiedSince; SQLiteDatabase db = serverDiffs.getDatabase(); db.beginTransaction(); try { modifiedSince = getServerDiffsImpl(context, serverDiffs, FEED_ARTISTS); if (modifiedSince >= 0) getImageData(context, serverDiffs, FEED_ARTISTS, modifiedSince); modifiedSince = getServerDiffsImpl(context, serverDiffs, FEED_ALBUMS); if (modifiedSince >= 0) getImageData(context, serverDiffs, FEED_ALBUMS, modifiedSince); getServerDiffsImpl(context, serverDiffs, FEED_SONGS); getServerDiffsImpl(context, serverDiffs, FEED_PLAYLISTS); getServerDiffsImpl(context, serverDiffs, FEED_PLAYLIST_SONGS); db.setTransactionSuccessful(); } finally { db.endTransaction(); } /* This is a very naive implementation... */ if (context.hasCanceled() == false && context.hasError() == false) context.moreRecordsToGet = false; }