List of usage examples for android.database.sqlite SQLiteDatabase OPEN_READWRITE
int OPEN_READWRITE
To view the source code for android.database.sqlite SQLiteDatabase OPEN_READWRITE.
Click Source Link
From source file:Main.java
private static boolean openDatabase() { String path = DB_PATH + DB_NAME; database = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READWRITE); return database != null; }
From source file:io.jawg.osmcontributor.utils.core.database.DatabaseUpgradeTest.java
@Test public void upgrade() throws Exception { System.out.println(new File(".").getAbsolutePath()); OsmSqliteOpenHelper openHelper = new OsmSqliteOpenHelper(Robolectric.application); SQLiteDatabase newDb = SQLiteDatabase.openOrCreateDatabase(newDbFile, null); openHelper.onCreate(newDb);//from www. j a v a2s . c o m SQLiteDatabase upgradedDb = SQLiteDatabase.openDatabase(updatedDbFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE); openHelper.onUpgrade(upgradedDb, 1, OsmSqliteOpenHelper.CURRENT_VERSION); openHelper.close(); Class.forName("org.sqlite.JDBC"); String baseJdbcUrl = "jdbc:sqlite:"; Set<String> newContents = extractContent(baseJdbcUrl + newDbFile.getAbsolutePath()); Set<String> updatedContents = extractContent(baseJdbcUrl + updatedDbFile.getAbsolutePath()); assertThat(updatedContents).containsAll(newContents); assertThat(updatedContents).isEqualTo(newContents); }
From source file:br.com.anteros.android.persistence.backup.ExportDatabaseTask.java
public static String executarBackup(String databaseName, String databasePath, SharedPreferences preferences, Context context) {/*from ww w . ja v a 2s . c o m*/ if (ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { throw new BackupException( "No foi possvel executar a tarefa de backup pois voc no possu permisso para isto. Verifique se solicitou permisso no manifesto ou requisitou a permisso caso esteja usando Android(Marshmallow) 6 ou acima."); } File dbFile = new File(databasePath); File exportDir = new File(Environment.getExternalStorageDirectory(), "backup"); if (!exportDir.exists()) { exportDir.mkdirs(); } if (countBackupFiles(exportDir, dbFile.getName()) >= maxBackupFiles) { deleteOldBackup(exportDir, dbFile.getName()); } lastBackup = new File(exportDir, generateBackupName(dbFile)); try { lastBackup.createNewFile(); AndroidFileUtils.copyFile(dbFile, lastBackup); SharedPreferences.Editor editor = preferences.edit(); editor.putLong(BackupService.DATE_TIME_LAST_BACKUP, new Date().getTime()); editor.commit(); } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } SQLiteDatabase db = null; try { db = context.openOrCreateDatabase(databaseName, SQLiteDatabase.OPEN_READWRITE, null); db.execSQL("vacuum;"); db.execSQL("reindex;"); } catch (Exception e) { e.printStackTrace(); } finally { try { db.close(); } catch (Exception e2) { } } return "OK"; }
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 ww w.ja v a2 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:org.thomnichols.android.gmarks.WebViewCookiesDB.java
public void deleteCookie(String key) { SQLiteDatabase db = openDatabase(SQLiteDatabase.OPEN_READWRITE); if (db == null) return;/* w ww. j ava 2 s . co m*/ try { db.delete(TABLE_NAME, COLUMNS[COL_NAME] + "=?", new String[] { key }); } catch (SQLiteException ex) { Log.w(TAG, "Error deleting cookie: " + key, ex); } finally { db.close(); } }
From source file:holidayiq.com.geofenced.geofence.GeofenceTransitionsIntentService.java
public static void SendNotificationForEntry(Context mContext, String geoId, String geoName, String notificationStringTitle, String notificationStringContent, String notificationStringDeeplink, String objType, Context context, String eventType, boolean isBanner) { String currentTime = String.valueOf(System.currentTimeMillis()); if (notificationStringTitle != null) { notificationStringTitle = notificationStringTitle.replace("$name$", geoName); notificationStringContent = notificationStringContent.replace("$name$", geoName); notificationStringDeeplink = notificationStringDeeplink.replace("$name$", Underscored(geoName)); notificationStringDeeplink = notificationStringDeeplink.replace("$id$", geoId); Calendar c = new GregorianCalendar(); c.set(Calendar.HOUR_OF_DAY, 6); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); Date d1 = c.getTime();//from w ww . ja va 2 s. com boolean isNotification = false; File dbFile = mContext.getDatabasePath("hiq_in_app.sqlite"); SQLiteDatabase inAppDb = SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READWRITE); if (geoName.equalsIgnoreCase("home")) { String lastTriggeredHome = HIQSharedPrefrence.getString("lastTriggeredHome", mContext); if (lastTriggeredHome == null) { sendNotification(notificationStringTitle, notificationStringContent, notificationStringDeeplink, context, isBanner); HIQSharedPrefrence.putString("lastTriggeredHome", System.currentTimeMillis() + "", mContext); isNotification = true; } else { long previouslastTriggeredHome = Long .parseLong(HIQSharedPrefrence.getString("lastTriggeredHome", mContext)); if (previouslastTriggeredHome < d1.getTime()) { sendNotification(notificationStringTitle, notificationStringContent, notificationStringDeeplink, context, isBanner); HIQSharedPrefrence.putString("lastTriggeredHome", System.currentTimeMillis() + "", mContext); isNotification = true; } } } else if (objType.equalsIgnoreCase("Hotel")) { String lastTriggeredHome = HIQSharedPrefrence.getString("lastTriggeredHotel", mContext); if (lastTriggeredHome == null) { sendNotification(notificationStringTitle, notificationStringContent, notificationStringDeeplink, context, isBanner); HIQSharedPrefrence.putString("lastTriggeredHotel", System.currentTimeMillis() + "", mContext); isNotification = true; } else { long previouslastTriggeredHome = Long .parseLong(HIQSharedPrefrence.getString("lastTriggeredHotel", mContext)); if (previouslastTriggeredHome < d1.getTime()) { sendNotification(notificationStringTitle, notificationStringContent, notificationStringDeeplink, context, isBanner); HIQSharedPrefrence.putString("lastTriggeredHotel", System.currentTimeMillis() + "", mContext); isNotification = true; } } } else if (objType.equalsIgnoreCase("SS")) { Cursor res = null; try { String lastNotificationTriggerd = null; res = inAppDb.rawQuery("Select * from " + GeoDbHelper.SIGHT_SEEING_TABLE_NAME + " where " + GeoDbHelper.SIGHT_SEEING_COULUMN_ID + " = " + geoId, null); if (res != null) { if (res.moveToFirst()) { lastNotificationTriggerd = res.getString(res.getColumnIndex("lastTimeStamp")); } } if (lastNotificationTriggerd == null) { sendNotification(notificationStringTitle, notificationStringContent, notificationStringDeeplink, context, isBanner); isNotification = true; Cursor cur = inAppDb.rawQuery("update " + GeoDbHelper.SIGHT_SEEING_TABLE_NAME + " SET lastTimeStamp = '" + currentTime + "' where " + GeoDbHelper.SIGHT_SEEING_COULUMN_ID + " = " + geoId, null); cur.moveToFirst(); cur.close(); } else { long time = Long.parseLong(lastNotificationTriggerd); if (time < d1.getTime()) { sendNotification(notificationStringTitle, notificationStringContent, notificationStringDeeplink, context, isBanner); isNotification = true; Cursor cur = inAppDb.rawQuery("update " + GeoDbHelper.SIGHT_SEEING_TABLE_NAME + " SET lastTimeStamp = '" + currentTime + "' where " + GeoDbHelper.SIGHT_SEEING_COULUMN_ID + " = " + geoId, null); cur.moveToFirst(); cur.close(); } } } catch (Exception e) { e.printStackTrace(); ExceptionUtils.logException(e); } finally { if (res != null && !res.isClosed()) { res.close(); } res = null; if (inAppDb != null && inAppDb.isOpen()) { inAppDb.close(); } inAppDb = null; } } else if (objType.equalsIgnoreCase("Destination")) { Cursor res = null; try { String lastNotificationTriggerd = null; res = inAppDb.rawQuery("Select * from " + GeoDbHelper.DESTINATION_TABLE_NAME + " where " + GeoDbHelper.DESTINATION_COLUMN_ID + " = " + geoId, null); if (res != null) { try { if (res.moveToFirst()) { lastNotificationTriggerd = res.getString(res.getColumnIndex("lastTimeStamp")); } } catch (Exception e) { } } if (lastNotificationTriggerd == null) { sendNotification(notificationStringTitle, notificationStringContent, notificationStringDeeplink, context, isBanner); isNotification = true; Cursor cur = inAppDb.rawQuery("update " + GeoDbHelper.DESTINATION_TABLE_NAME + " SET lastTimeStamp = '" + currentTime + "' where " + GeoDbHelper.DESTINATION_COLUMN_ID + " = " + geoId, null); cur.moveToFirst(); cur.close(); } else { long time = Long.parseLong(lastNotificationTriggerd); if (time < d1.getTime()) { sendNotification(notificationStringTitle, notificationStringContent, notificationStringDeeplink, context, isBanner); isNotification = true; Cursor cur = inAppDb.rawQuery("update " + GeoDbHelper.DESTINATION_TABLE_NAME + " SET lastTimeStamp = '" + currentTime + "' where " + GeoDbHelper.DESTINATION_COLUMN_ID + " = " + geoId, null); cur.moveToFirst(); cur.close(); } } } catch (Exception e) { ExceptionUtils.logException(e); } finally { if (res != null && !res.isClosed()) { res.close(); } res = null; if (inAppDb != null && inAppDb.isOpen()) { inAppDb.close(); } inAppDb = null; } } HashMap<String, Object> oMap = new HashMap<String, Object>(); oMap.put("Type", eventType); oMap.put("Name", geoName); oMap.put("ID", geoId); oMap.put("Object Type", objType); oMap.put("Date", new Date()); if (isNotification) { } } // HIQUtil.sendEventToGAFromObject("GeoFenceEvent", "GeoFenceEvent in Android", oMap); }
From source file:org.thomnichols.android.gmarks.WebViewCookiesDB.java
public void deleteAllCookies() { SQLiteDatabase db = openDatabase(SQLiteDatabase.OPEN_READWRITE); if (db == null) return;/* ww w .ja v a 2 s.c om*/ try { db.delete(TABLE_NAME, null, null); } catch (SQLiteException ex) { Log.w(TAG, "Error deleting cookies", ex); } finally { db.close(); } }
From source file:com.ideateam.plugin.DownloadDB.java
private DeviceDB GetDeviceDB(String dbName) { DeviceDB dDB = new DeviceDB(); String path = cordova.getActivity().getApplicationContext().getFilesDir().getPath(); String dbPath = path.substring(0, path.lastIndexOf("/")) + "/app_database/"; Log.d(TAG, dbPath);//from w ww .j av a 2 s .c o m File file = new File(dbPath + "Databases.db"); if (!file.exists()) { Log.d(TAG, "Databases.db not found"); dbPath = path.substring(0, path.lastIndexOf("/")) + "/app_webview/databases/"; } dDB.master_db = SQLiteDatabase.openDatabase(dbPath + "Databases.db", null, SQLiteDatabase.OPEN_READWRITE); try { Cursor c = dDB.master_db.rawQuery("SELECT origin, path FROM Databases WHERE name='" + dbName + "'", null); c.moveToFirst(); dDB.cordovaDBPath = dbPath + c.getString(0) + "/"; dDB.cordovaDBName = c.getString(1); c.close(); } catch (Exception e) { Log.d(TAG, "Can not found fields ORIGIN, PATH"); Cursor c = dDB.master_db.rawQuery("SELECT origin, id FROM Databases WHERE name='" + dbName + "'", null); c.moveToFirst(); dDB.cordovaDBPath = dbPath + c.getString(0) + "/"; dDB.cordovaDBName = c.getString(1) + ".db"; c.close(); } return dDB; }
From source file:org.liberty.android.fantastischmemopro.DatabaseHelper.java
public void openDatabase() throws SQLException { String myPath = dbPath + "/" + dbName; Cursor result;/*from w ww . ja v a 2 s.co m*/ int count_dict = 0, count_learn = 0; myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); result = myDatabase.rawQuery("SELECT _id FROM dict_tbl", null); count_dict = result.getCount(); result.close(); if (count_dict == 0) { return; } result = myDatabase.rawQuery("SELECT _id FROM learn_tbl", null); count_learn = result.getCount(); result.close(); if (count_learn != count_dict) { /* Reconstruct learn_tbl if error found */ this.myDatabase.execSQL("DELETE FROM learn_tbl"); this.myDatabase.execSQL("INSERT INTO learn_tbl(_id) SELECT _id FROM dict_tbl"); this.myDatabase.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"); } }
From source file:uk.org.rivernile.edinburghbustracker.android.Application.java
/** * Download the stop database from the server and put it in the * application's working data directory. * * @param context The context to use this method with. * @param url The URL of the bus stop database to download. *///from www . j av a 2 s . c om private static void updateStopsDB(final Context context, final String url, final String checksum) { if (context == null || url == null || url.length() == 0 || checksum == null || checksum.length() == 0) return; try { // Connect to the server. final URL u = new URL(url); final HttpURLConnection con = (HttpURLConnection) u.openConnection(); final InputStream in = con.getInputStream(); // Make sure the URL is what we expect. if (!u.getHost().equals(con.getURL().getHost())) { in.close(); con.disconnect(); return; } // The location the file should be downloaded to. final File temp = context.getDatabasePath(BusStopDatabase.STOP_DB_NAME + "_temp"); // The eventual destination of the file. final File dest = context.getDatabasePath(BusStopDatabase.STOP_DB_NAME); final FileOutputStream out = new FileOutputStream(temp); // Get the file from the server. byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } // Make sure the stream is flushed then close resources and // disconnect. out.flush(); out.close(); in.close(); con.disconnect(); // Do a MD5 checksum on the downloaded file. Make sure it matches // what the server reported. if (!md5Checksum(temp).equalsIgnoreCase(checksum)) { // If it doesn't match, delete the downloaded file. temp.delete(); return; } try { // Open the temp database and execute the index operation on it. final SQLiteDatabase db = SQLiteDatabase.openDatabase(temp.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE); BusStopDatabase.setUpIndexes(db); db.close(); } catch (SQLiteException e) { // If we couldn't create the index, continue anyway. The user // will still be able to use the database, it will just run // slowly if they want route lines. } // Close a currently open database. Delete the old database then // move the downloaded file in to its place. Do this while // synchronized to make sure noting else uses the database in this // time. final BusStopDatabase bsd = BusStopDatabase.getInstance(context.getApplicationContext()); synchronized (bsd) { try { bsd.getReadableDatabase().close(); } catch (SQLiteException e) { // Nothing to do here. Assume it's already closed. } dest.delete(); temp.renameTo(dest); } // Delete the associated journal file because we no longer need it. final File journalFile = context.getDatabasePath(BusStopDatabase.STOP_DB_NAME + "_temp-journal"); if (journalFile.exists()) journalFile.delete(); // Alert the user that the database has been updated. Looper.prepare(); Toast.makeText(context, R.string.bus_stop_db_updated, Toast.LENGTH_LONG).show(); Looper.loop(); } catch (MalformedURLException e) { } catch (IOException e) { } }