private ApnDatabase(final Context context) throws IOException { this.context = context; File dbFile = context.getDatabasePath(DATABASE_NAME); if (!dbFile.getParentFile().exists() && !dbFile.getParentFile().mkdir()) { throw new IOException("couldn't make databases directory"); } Util.copy(context.getAssets().open(ASSET_PATH, AssetManager.ACCESS_STREAMING), new FileOutputStream(dbFile)); try { this.db = SQLiteDatabase.openDatabase(context.getDatabasePath(DATABASE_NAME).getPath(), null, SQLiteDatabase.OPEN_READONLY | SQLiteDatabase.NO_LOCALIZED_COLLATORS); } catch (SQLiteException e) { throw new IOException(e); } }
public static void changeThreadingIndexes(SQLiteDatabase db) { try { db.execSQL("DROP INDEX IF EXISTS msg_empty"); db.execSQL("CREATE INDEX IF NOT EXISTS msg_empty ON messages (empty)"); db.execSQL("DROP INDEX IF EXISTS msg_thread_root"); db.execSQL("CREATE INDEX IF NOT EXISTS msg_thread_root ON messages (thread_root)"); db.execSQL("DROP INDEX IF EXISTS msg_thread_parent"); db.execSQL("CREATE INDEX IF NOT EXISTS msg_thread_parent ON messages (thread_parent)"); } catch (SQLiteException e) { if (!e.getMessage().startsWith("duplicate column name:")) { throw e; } } }
public Database.ExecuteSQLResponse executeSQL(String databaseName, String query, ExecuteResultHandler<Database.ExecuteSQLResponse> handler) throws SQLiteException { Util.throwIfNull(query); Util.throwIfNull(handler); SQLiteDatabase database = openDatabase(databaseName); try { String firstWordUpperCase = getFirstWord(query).toUpperCase(); switch (firstWordUpperCase) { case "UPDATE": case "DELETE": return executeUpdateDelete(database, query, handler); case "INSERT": return executeInsert(database, query, handler); case "SELECT": case "PRAGMA": case "EXPLAIN": return executeSelect(database, query, handler); default: return executeRawQuery(database, query, handler); } } finally { database.close(); } }
/** * * @throws UnavailableStorageException */ private void openOrCreateDataspace() throws UnavailableStorageException { lockWrite(); try { final File databaseFile = prepareStorage(mStorageProviderId); try { doOpenOrCreateDb(databaseFile); } catch (SQLiteException e) { // TODO handle this error in a better way! Timber.w(e, "Unable to open DB %s - removing file and retrying", databaseFile); if (databaseFile.exists() && !databaseFile.delete()) { Timber.d("Failed to remove %s that couldn't be opened", databaseFile); } doOpenOrCreateDb(databaseFile); } if (mDb.getVersion() != mSchemaDefinition.getVersion()) { mSchemaDefinition.doDbUpgrade(mDb); } } finally { unlockWrite(); } }
public boolean getSystemBrowser() { Cursor c = null; String[] columns = new String[] { "url", "title" }; boolean browserFlag; try { //Uri bookmarks = Browser.BOOKMARKS_URI; //c = getContentResolver().query(bookmarks, columns, null, null, null); } catch (SQLiteException | IllegalStateException | NullPointerException e) { e.printStackTrace(); } if (c != null) { Log.d("Browser", "System Browser Available"); browserFlag = true; } else { Log.e("Browser", "System Browser Unavailable"); browserFlag = false; } if (c != null) { c.close(); } mPreferences.setSystemBrowserPresent(browserFlag); return browserFlag; }
/** * @throws SQLiteException */ public void openDatabase() throws SQLiteException { openHelper = new DBOpenHelper(context, MD5Utils.GetMD5Code("kf5_ticket_" + SPUtils.getUserId()) + ".db", null, VERSION); try { db = openHelper.getWritableDatabase(); } catch (SQLiteException e) { e.printStackTrace(); db = openHelper.getReadableDatabase(); } boolean isTableExit = tableIsExist(openHelper, DB_TABLE); if (!isTableExit) { db.execSQL(DB_CREATE); } }
public List<String> getTableNames(String databaseName) throws SQLiteException { SQLiteDatabase database = openDatabase(databaseName); try { Cursor cursor = database.rawQuery("SELECT name FROM sqlite_master WHERE type IN (?, ?)", new String[]{"table", "view"}); try { List<String> tableNames = new ArrayList<String>(); while (cursor.moveToNext()) { tableNames.add(cursor.getString(0)); } return tableNames; } finally { cursor.close(); } } finally { database.close(); } }
/** * @param isGetAll true if want to get all subject * @param teacher_id Integer * @return {@link ArrayList<Subject>} * @throws NullObjectException if connect to database fail or day_start after day_end */ public ArrayList<Subject> getSubjectList(Boolean isGetAll, @Nonnegative Integer teacher_id) throws NullObjectException { SQLiteDatabase db; try { db = this.getReadableDatabase(); } catch (SQLiteException e) { Log.d(TAG, "getSubjectList error: " + e.toString()); throw new NullObjectException(mDBStringHelper.getDBString(DATABASE_CODE.CONNECT_FAIL)); } String query; if (isGetAll) { query = "SELECT * FROM " + TABLE_SUBJECTS; } else if (teacher_id != null) { query = "SELECT * FROM " + TABLE_SUBJECTS + " WHERE " + Teacher_ID + " = " + teacher_id; } else { return new ArrayList<>(); } return getSubjectListByQuery(query, db); }
/** * @param subject_id Integer * @param subject_name String * @return Subject * @throws NullObjectException if connect to database fail or not found subject */ public Subject getSubject(@Nonnegative @Nullable Integer subject_id, @Nullable String subject_name) throws NullObjectException { SQLiteDatabase db; try { db = this.getReadableDatabase(); } catch (SQLiteException e) { Log.d(TAG, "getSubject error:" + e.toString()); throw new NullObjectException(mDBStringHelper.getDBString(DATABASE_CODE.CONNECT_FAIL)); } String query; if (subject_id != null) { query = "SELECT * FROM " + TABLE_SUBJECTS + " WHERE " + Subjects_ID + " = " + subject_id; } else if (subject_name != null) { query = "SELECT * FROM " + TABLE_SUBJECTS + " WHERE " + Subjects_Name + " = '" + subject_name + "'"; } else { Log.d(TAG, "getSubject error: Not found subject"); throw new NullObjectException(mDBStringHelper.getDBString(DATABASE_CODE.NOT_FOUND_SUBJECT)); } return getSubjectByQuery(query, db); }
/** * Delete a subject * * @param subject_id subject id * @return DATABASE_CODE */ public DATABASE_CODE deleteSubject(@Nonnegative int subject_id) { SQLiteDatabase db; try { db = this.getWritableDatabase(); } catch (SQLiteException e) { Log.d(TAG, "deleteSubject error: " + e.toString()); return DATABASE_CODE.CONNECT_FAIL; } String whereClause = Subjects_ID + " = " + subject_id; if (db.delete(TABLE_SUBJECTS, whereClause, null) != 0) { Log.d(TAG, "deleteSubject success"); return DATABASE_CODE.DELETE_SUBJECT_SUCCESS; } Log.d(TAG, "deleteSubject error"); return DATABASE_CODE.DELETE_SUBJECT_FAIL; }
/** * @param repeat_id Integer * @param repeat_name String * @return Repeat * @throws NullObjectException if connect to database fail or not found repeat */ public Repeat getRepeat(@Nonnegative Integer repeat_id, String repeat_name) throws NullObjectException { SQLiteDatabase db; try { db = this.getReadableDatabase(); } catch (SQLiteException e) { Log.d(TAG, "getRepeat error: " + e.toString()); throw new NullObjectException(mDBStringHelper.getDBString(DATABASE_CODE.CONNECT_FAIL)); } String query; if (repeat_id != null) { query = "SELECT * FROM " + TABLE_REPEAT + " WHERE " + Repeat_ID + " = " + repeat_id; } else if (repeat_name != null) { query = "SELECT * FROM " + TABLE_REPEAT + " WHERE " + Repeat_Name + " = '" + repeat_name + "'"; } else { Log.d(TAG, "getRepeat error: Not found repeat"); throw new NullObjectException(mDBStringHelper.getDBString(DATABASE_CODE.NOT_FOUND_REPEAT)); } return getRepeatByQuery(query, db); }
/** * @param subject_id Integer * @return {@link ArrayList<WeekLesson>} * @throws NullObjectException if connect database fail or day_start after day_end */ public ArrayList<WeekLesson> getWeekLessonList(Integer subject_id) throws NullObjectException { SQLiteDatabase db; try { db = this.getReadableDatabase(); } catch (SQLiteException e) { Log.d(TAG, "getWeekLessonList error: " + e.toString()); throw new NullObjectException(mDBStringHelper.getDBString(DATABASE_CODE.CONNECT_FAIL)); } String query; if (subject_id != null) { query = "SELECT * FROM " + TABLE_WEEK_LESSON + " WHERE " + Subjects_ID + " = " + subject_id; } else { query = "SELECT * FROM " + TABLE_WEEK_LESSON; } return getWeekLessonListByQuery(query, db); }
/** * Prints the contents of a Cursor's current row to a StringBuilder. * * @param cursor the cursor to print * @param sb the StringBuilder to print to */ public static void dumpCurrentRow(Cursor cursor, StringBuilder sb) { String[] cols = cursor.getColumnNames(); sb.append("" + cursor.getPosition() + " {\n"); int length = cols.length; for (int i = 0; i < length; i++) { String value; try { value = cursor.getString(i); } catch (SQLiteException e) { // assume that if the getString threw this exception then the column is not // representable by a string, e.g. it is a BLOB. value = "<unprintable>"; } sb.append(" " + cols[i] + '=' + value + "\n"); } sb.append("}\n"); }
private static final void readExceptionFromParcel(Parcel reply, String msg, int code) { switch (code) { case 2: throw new IllegalArgumentException(msg); case 3: throw new UnsupportedOperationException(msg); case 4: throw new SQLiteAbortException(msg); case 5: throw new SQLiteConstraintException(msg); case 6: throw new SQLiteDatabaseCorruptException(msg); case 7: throw new SQLiteFullException(msg); case 8: throw new SQLiteDiskIOException(msg); case 9: throw new SQLiteException(msg); case 11: throw new OperationCanceledException(msg); default: reply.readException(code, msg); } }
/** * @param location_id Integer * @param location_name Integer * @return Location * @throws NullObjectException if connect to database fail or not found location */ public Location getLocation(@Nonnegative Integer location_id, String location_name) throws NullObjectException { SQLiteDatabase db; try { db = this.getReadableDatabase(); } catch (SQLiteException e) { Log.d(TAG, "getLocation error: " + e.toString()); throw new NullObjectException(mDBStringHelper.getDBString(DATABASE_CODE.CONNECT_FAIL)); } String selectQuery; if (location_id != null) { selectQuery = "SELECT * FROM " + TABLE_LOCATION + " WHERE " + Location_ID + " = " + location_id; } else if (location_name != null) { selectQuery = "SELECT * FROM " + TABLE_LOCATION + " WHERE " + Location_Name + " = '" + location_name + "'"; } else { Log.d(TAG, "getLocation error: Not found location"); throw new NullObjectException(mDBStringHelper.getDBString(DATABASE_CODE.NOT_FOUND_LOCATION)); } return getLocationByQuery(selectQuery, db); }
/** * @param location_id location_id * @return {@link DATABASE_CODE#CONNECT_FAIL},{@link DATABASE_CODE#DELETE_LOCATION_SUCCESS},{@link DATABASE_CODE#DELETE_LOCATION_FAIL} */ public DATABASE_CODE deleteLocation(@Nonnegative int location_id) { SQLiteDatabase db; try { db = this.getWritableDatabase(); } catch (SQLiteException e) { Log.d(TAG, "deleteLocation error: " + e.toString()); return DATABASE_CODE.CONNECT_FAIL; } String whereClause = Location_ID + " = " + location_id; //Deleting a record if (db.delete(TABLE_LOCATION, whereClause, null) != 0) { Log.d(TAG, "deleteLocation success"); return DATABASE_CODE.DELETE_LOCATION_SUCCESS; } Log.d(TAG, "deleteLocation error"); return DATABASE_CODE.DELETE_LOCATION_FAIL; }
public static boolean execute(Worker worker) { SQLiteDatabase db = Orm.getDatabase(); db.beginTransaction(); try { boolean isOk = worker.doTransition(db); if (isOk) { db.setTransactionSuccessful(); } return isOk; } catch(SQLiteException e) { e.printStackTrace(); } finally { db.endTransaction(); } return false; }
/** * @param day_lesson_id day_lesson_id * @return {@link DATABASE_CODE#CONNECT_FAIL}, {@link DATABASE_CODE#DELETE_DAY_LESSON_SUCCESS} * ,{@link DATABASE_CODE#DELETE_DAY_LESSON_FAIL} */ public DATABASE_CODE deleteDayLesson(int day_lesson_id) { SQLiteDatabase db; try { db = this.getWritableDatabase(); } catch (SQLiteException e) { Log.d(TAG, "deleteDayLesson error: " + e.toString()); return DATABASE_CODE.CONNECT_FAIL; } String whereClause = DayLesson_ID + " = " + day_lesson_id; if (db.delete(TABLE_DAY_LESSON, whereClause, null) != 0) { Log.d(TAG, "deleteDayLesson success"); return DATABASE_CODE.DELETE_DAY_LESSON_SUCCESS; } Log.d(TAG, "deleteDayLesson error"); return DATABASE_CODE.DELETE_DAY_LESSON_FAIL; }
@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { switch (oldVersion) { case 0: try { db.execSQL("CREATE TABLE main.history " + "(_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "url TEXT NOT NULL, " + "code TEXT NOT NULL," + "date INTEGER NOT NULL)"); db.execSQL("CREATE TABLE main.params " + "(_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "kind TEXT NOT NULL, " + "value TEXT)"); } catch (SQLiteException e) { Log.e("db", "onUpgrade", e); } } }
/** * Check if the database already exist to avoid re-copying the file each time you open the application. * * ToDo: NOTE: This is a dumb check, as it currently only tries to open it. * It may be other reasons why it can't be opened even if it already exists. * * @return true if it exists, false if it doesn't */ private boolean checkDataBase() { SQLiteDatabase checkDB = null; try { Log.i(TAG, mTAG + "Checking if DB exists..."); checkDB = SQLiteDatabase.openDatabase(mDatabasePath, null, SQLiteDatabase.OPEN_READONLY); } catch (SQLiteException e) { Log.i(TAG, mTAG + "SQL Exception! Database can\'t be opened: " + e); //Log.i(TAG, mTAG + "Database not yet created: " + e); } if (checkDB != null) { checkDB.close(); Log.i(TAG, mTAG + "OK (found)"); return true; } Log.i(TAG, mTAG + "Database probably not yet created."); return false; }
private ArrayList<Integer> getUsersNotToNotify(SQLiteDatabase db) throws SQLiteException { String query = "SELECT * FROM " + SubscriptionsDbHelper.TABLE_NAME + " WHERE " + SubscriptionsDbHelper.COLUMN_NOTIFY_WHEN_LIVE + "=" + 0 + ";"; Cursor cursor = db.rawQuery(query, null); ArrayList<Integer> usersToNotify = new ArrayList<>(); while(cursor.moveToNext()) { int idPosition = cursor.getColumnIndex(SubscriptionsDbHelper.COLUMN_ID); int userId = cursor.getInt(idPosition); usersToNotify.add(userId); } cursor.close(); return usersToNotify; }
public void trimHistory() { SQLiteOpenHelper helper = new DBHelper(activity); SQLiteDatabase db = null; Cursor cursor = null; try { db = helper.getWritableDatabase(); cursor = db.query(DBHelper.TABLE_NAME, ID_COL_PROJECTION, null, null, null, null, DBHelper.TIMESTAMP_COL + " DESC"); cursor.move(MAX_ITEMS); while (cursor.moveToNext()) { String id = cursor.getString(0); Log.i(TAG, "Deleting scan history ID " + id); db.delete(DBHelper.TABLE_NAME, DBHelper.ID_COL + '=' + id, null); } } catch (SQLiteException sqle) { // We're seeing an error here when called in CaptureActivity.onCreate() in rare cases // and don't understand it. First theory is that it's transient so can be safely ignored. Log.w(TAG, sqle); // continue } finally { close(cursor, db); } }
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (cursor != null) { Set<String> mBookedPrograms = new HashSet(); while (cursor.moveToNext()) { try { int idx = cursor.getColumnIndexOrThrow(Field.MD5_ID); if (idx != -1) { mBookedPrograms.add(cursor.getString(idx)); } } catch (SQLiteException e) { e.printStackTrace(); return; } } if (this.mAdapter != null) { this.mAdapter.setBookedPrograms(mBookedPrograms); } } }
public void transactionFailed() throws SQLiteIOException { close(); SQLiteDatabase writableDatabase = siteToSiteDB.getWritableDatabase(); writableDatabase.beginTransaction(); try { ContentValues contentValues = new ContentValues(); contentValues.putNull(DATA_PACKET_QUEUE_TRANSACTION_COLUMN); writableDatabase.update(DATA_PACKET_QUEUE_TABLE_NAME, contentValues, DATA_PACKET_QUEUE_TRANSACTION_COLUMN + " = ?", new String[] {Long.toString(transactionId)}); writableDatabase.delete(DATA_PACKET_QUEUE_TRANSACTIONS_TABLE_NAME, DATA_PACKET_QUEUE_TRANSACTION_COLUMN + " = ?", new String[] {Long.toString(transactionId)}); writableDatabase.setTransactionSuccessful(); } catch (SQLiteException e) { throw new SQLiteIOException("Unable to clear transaction from failed data packets.", e); } finally { writableDatabase.endTransaction(); writableDatabase.close(); } }
/** * Check if the database already exist to avoid re-copying the file each time you open the * application. * * @return true if it exists, false if it doesn't */ private boolean checkDataBase() { SQLiteDatabase checkDB = null; try { String myPath = DB_PATH + DB_NAME; checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); } catch (SQLiteException e) { // database doesn't exist yet. } if (checkDB != null) { checkDB.close(); } return checkDB != null ? true : false; }
@Nullable @Override public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) throws UnsupportedOperationException, SQLiteException { final SQLiteDatabase db = mDbHelper.getWritableDatabase(); int match = sUriMatcher.match(uri); long res = -1; switch (match) { case FAVORITES_WITH_ID: List<String> pathSegments = uri.getPathSegments(); if (pathSegments != null && pathSegments.size() > 2) { String type = pathSegments.get(1); String id = pathSegments.get(2); if (values != null) { values.put(MediaEntry.COLUMN_IS_FAVORED, 1); values.put(MediaEntry.COLUMN_MEDIA_TYPE, type); int numRows = db.update(MediaEntry.TABLE_NAME, values, MediaEntry.COLUMN_MEDIA_TYPE + " = ? AND " + MediaEntry.COLUMN_MEDIA_ID + " = ? ", new String[]{type, id}); if (numRows <= 0) { res = db.insert(MediaEntry.TABLE_NAME, null, values); if (res == -1) { throw new SQLiteException("Failed to insert record: " + uri); } } } } break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } mContext.getContentResolver().notifyChange(uri, null); return ContentUris.withAppendedId(uri, res); }
public static void addDeletedColumn(SQLiteDatabase db) { try { db.execSQL("ALTER TABLE messages ADD deleted INTEGER default 0"); } catch (SQLiteException e) { if (!e.toString().startsWith("duplicate column name: deleted")) { throw e; } } }
public static void addAttachmentsContentIdColumn(SQLiteDatabase db) { try { db.execSQL("ALTER TABLE attachments ADD content_id TEXT"); } catch (SQLiteException e) { Timber.e("Unable to add content_id column to attachments"); } }
public static void addMimeTypeColumn(SQLiteDatabase db) { try { db.execSQL("ALTER TABLE messages ADD mime_type TEXT"); } catch (SQLiteException e) { Timber.e("Unable to add mime_type column to messages"); } }
@SuppressWarnings("BooleanMethodIsAlwaysInverted") private boolean columnExists(SQLiteDatabase db, String table, String column) { String testSql = "SELECT " + column + " FROM " + table + " WHERE 1=2"; try { db.rawQuery(testSql, null); return true; } catch (SQLiteException e) { return false; } }
public static void addMessagesThreadingColumns(SQLiteDatabase db) { try { db.execSQL("ALTER TABLE messages ADD thread_root INTEGER"); db.execSQL("ALTER TABLE messages ADD thread_parent INTEGER"); db.execSQL("ALTER TABLE messages ADD normalized_subject_hash INTEGER"); db.execSQL("ALTER TABLE messages ADD empty INTEGER"); } catch (SQLiteException e) { if (!e.getMessage().startsWith("duplicate column name:")) { throw e; } } }
@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { try { if (newVersion == 7) { new Settings(mContext).setUsersNotToNotifyWhenLive(getUsersNotToNotify(db)); } } catch (SQLiteException e) { e.printStackTrace(); } db.execSQL(SQL_DELETE_ENTRIES); onCreate(db); //db.close(); }
public static void updateRemoveXNoSeenInfoFlag(SQLiteDatabase db) { try { db.execSQL("update messages set flags = replace(flags, 'X_NO_SEEN_INFO', 'X_BAD_FLAG')"); } catch (SQLiteException e) { Timber.e(e, "Unable to get rid of obsolete flag X_NO_SEEN_INFO"); } }
public void close() { try { mDbHelper.close(); mDbHelper = null; mDb.close(); mDb = null; } catch (SQLiteException ignored) { } }
public void testUpdateWithStaticUpdateButWrongClass() { ContentValues values = new ContentValues(); values.put("TEACHERNAME", "Toy"); try { DataSupport.update(Object.class, values, teacher.getId()); } catch (SQLiteException e) { } }
public void testUpdateWithStaticUpdateButWrongColumn() { ContentValues values = new ContentValues(); values.put("TEACHERYEARS", 13); try { DataSupport.update(Teacher.class, values, teacher.getId()); fail("no such column: TEACHERYEARS"); } catch (SQLiteException e) { } }
@Override public final void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { try { onRobustUpgrade(db, oldVersion, newVersion); } catch (SQLiteException e) { // The database has entered an unknown state. Try to recover. try { regenerateTables(db); } catch (SQLiteException e2) { dropAndCreateTables(db); } } }
@Override public void onRobustUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) throws SQLiteException { switch (oldVersion) { case 1: db.execSQL("ALTER TABLE " + TABLE_PUBKEYS + " ADD COLUMN " + FIELD_PUBKEY_CONFIRMUSE + " INTEGER DEFAULT 0"); db.execSQL("ALTER TABLE " + TABLE_PUBKEYS + " ADD COLUMN " + FIELD_PUBKEY_LIFETIME + " INTEGER DEFAULT 0"); } }