public HistoryItem buildHistoryItem(int number) { SQLiteOpenHelper helper = new DBHelper(activity); SQLiteDatabase db = null; Cursor cursor = null; try { db = helper.getReadableDatabase(); cursor = db.query( DBHelper.TABLE_NAME, COLUMNS, null, null, null, null, DBHelper.TIMESTAMP_COL + " DESC"); cursor.move(number + 1); String text = cursor.getString(0); String display = cursor.getString(1); String format = cursor.getString(2); long timestamp = cursor.getLong(3); String details = cursor.getString(4); Result result = new Result(text, null, null, BarcodeFormat.valueOf(format), timestamp); return new HistoryItem(result, display, details); } finally { close(cursor, db); } }
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 addHistoryItem(Result result, ResultHandler handler) { // Do not save this item to the history if the preference is turned off, or the contents are // considered secure. if (!activity.getIntent().getBooleanExtra(Intents.Scan.SAVE_HISTORY, true) || handler.areContentsSecure() || !enableHistory) { return; } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity); if (!prefs.getBoolean(PreferencesActivity.KEY_REMEMBER_DUPLICATES, false)) { deletePrevious(result.getText()); } ContentValues values = new ContentValues(); values.put(DBHelper.TEXT_COL, result.getText()); values.put(DBHelper.FORMAT_COL, result.getBarcodeFormat().toString()); values.put(DBHelper.DISPLAY_COL, handler.getDisplayContents().toString()); values.put(DBHelper.TIMESTAMP_COL, System.currentTimeMillis()); SQLiteOpenHelper helper = new DBHelper(activity); SQLiteDatabase db = null; try { db = helper.getWritableDatabase(); // Insert the new entry into the DB. db.insert(DBHelper.TABLE_NAME, DBHelper.TIMESTAMP_COL, values); } finally { close(null, db); } }
public List<HistoryItem> buildHistoryItems() { SQLiteOpenHelper helper = new DBHelper(activity); List<HistoryItem> items = new ArrayList<>(); SQLiteDatabase db = null; Cursor cursor = null; try { db = helper.getReadableDatabase(); cursor = db.query( DBHelper.TABLE_NAME, COLUMNS, null, null, null, null, DBHelper.TIMESTAMP_COL + " DESC"); while (cursor.moveToNext()) { String text = cursor.getString(0); String display = cursor.getString(1); String format = cursor.getString(2); long timestamp = cursor.getLong(3); String details = cursor.getString(4); Result result = new Result(text, null, null, BarcodeFormat.valueOf(format), timestamp); items.add(new HistoryItem(result, display, details)); } } finally { close(cursor, db); } return items; }
@Override protected Boolean doInBackground(String... params) { Query query = new Query(); SQLiteOpenHelper openHelper = new DatabaseHelper(SettingConnections.context); SQLiteDatabase db = openHelper.getReadableDatabase(); cities = CitiesFactory.getCitiesFromCursor(query.selectCityLikeName(db, params[0])); db.close(); return true; }
@Override public void onDestroy() { super.onDestroy(); if (databaseHelpers != null) { for (SQLiteOpenHelper dbHelper : databaseHelpers.values()) { dbHelper.close(); } } Log.i(LogUtil.TAG, "Destroyed"); }
private void deletePrevious(String text) { SQLiteOpenHelper helper = new DBHelper(activity); SQLiteDatabase db = null; try { db = helper.getWritableDatabase(); db.delete(DBHelper.TABLE_NAME, DBHelper.TEXT_COL + "=?", new String[] {text}); } finally { close(null, db); } }
void clearHistory() { SQLiteOpenHelper helper = new DBHelper(activity); SQLiteDatabase db = null; try { db = helper.getWritableDatabase(); db.delete(DBHelper.TABLE_NAME, null, null); } finally { close(null, db); } }
private void runArchive(String databaseName) { SQLiteOpenHelper dbHelper = getOrCreateDatabaseHelper(databaseName); File dbFile = new File(dbHelper.getReadableDatabase().getPath()); Log.i(LogUtil.TAG, "Running archive: " + dbFile.getAbsolutePath()); dbHelper.close(); FileArchive archive = getArchive(databaseName); if (archive.add(dbFile)) { dbFile.delete(); } }
public DataManagerImpl(Context context) { this.context = context; SQLiteOpenHelper openHelper = new OpenHelper(this.context); db = openHelper.getWritableDatabase(); // Log.i(Constants.LOG_TAG, "DataManagerImpl created, db open status: " + db.isOpen()); priceHistoryDao = new PriceHistoryDao(db); itemDao = new ItemDao(db); }
public boolean hasHistoryItems() { SQLiteOpenHelper helper = new DBHelper(activity); SQLiteDatabase db = null; Cursor cursor = null; try { db = helper.getReadableDatabase(); cursor = db.query(DBHelper.TABLE_NAME, COUNT_COLUMN, null, null, null, null, null); cursor.moveToFirst(); return cursor.getInt(0) > 0; } finally { close(cursor, db); } }
protected void runArchive() { SQLiteDatabase db = databaseHelper.getWritableDatabase(); // TODO: add check to make sure this is not empty File dbFile = new File(db.getPath()); db.close(); if (archive.add(dbFile)) { dbFile.delete(); } reloadDbHelper(manager); db = databaseHelper.getWritableDatabase(); // Build new database db.close(); }
/** Deletes a row in the database */ @Override public int delete(final Uri uri, final String where, final String[] whereArgs) { Helpers.validateSelection(where, sAppReadableColumnsSet); SQLiteDatabase db = mOpenHelper.getWritableDatabase(); int count; int match = sURIMatcher.match(uri); switch (match) { case MY_DOWNLOADS: case MY_DOWNLOADS_ID: case ALL_DOWNLOADS: case ALL_DOWNLOADS_ID: SqlSelection selection = getWhereClause(uri, where, whereArgs, match); deleteRequestHeaders(db, selection.getSelection(), selection.getParameters()); count = db.delete(DB_TABLE, selection.getSelection(), selection.getParameters()); break; default: Log.d(Constants.TAG, "deleting unknown/invalid URI: " + uri); throw new UnsupportedOperationException("Cannot delete URI: " + uri); } notifyContentChanged(uri, match); return count; }
public Uri insert(Uri paramUri, ContentValues paramContentValues) { SQLiteDatabase localSQLiteDatabase = mOpenHelper.getWritableDatabase(); int i = paramUri.getPathSegments().size(); if (i < 1) { throw new IllegalArgumentException("Unknown Uri"); } long l2 = -1L; String str = (String) paramUri.getPathSegments().get(0); Object localObject = null; paramUri = (Uri) localObject; long l1 = l2; if (str.equals("suggestions")) { paramUri = (Uri) localObject; l1 = l2; if (i == 1) { l2 = localSQLiteDatabase.insert("suggestions", "query", paramContentValues); paramUri = (Uri) localObject; l1 = l2; if (l2 > 0L) { paramUri = Uri.withAppendedPath(mSuggestionsUri, String.valueOf(l2)); l1 = l2; } } } if (l1 < 0L) { throw new IllegalArgumentException("Unknown Uri"); } getContext().getContentResolver().notifyChange(paramUri, null); return paramUri; }
@Override public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException { HashSet<Uri> urisToNotify = new HashSet<Uri>(operations.size()); for (ContentProviderOperation operation : operations) { urisToNotify.add(operation.getUri()); } SQLiteDatabase db = mSqLiteOpenHelper.getWritableDatabase(); db.beginTransaction(); try { int numOperations = operations.size(); ContentProviderResult[] results = new ContentProviderResult[numOperations]; int i = 0; for (ContentProviderOperation operation : operations) { results[i] = operation.apply(this, results, i); if (operation.isYieldAllowed()) { db.yieldIfContendedSafely(); } i++; } db.setTransactionSuccessful(); for (Uri uri : urisToNotify) { getContext().getContentResolver().notifyChange(uri, null); } return results; } finally { db.endTransaction(); } }
@Override public int bulkInsert(Uri uri, ContentValues[] values) { String table = uri.getLastPathSegment(); SQLiteDatabase db = mSqLiteOpenHelper.getWritableDatabase(); int res = 0; db.beginTransaction(); try { for (ContentValues v : values) { long id = db.insert(table, null, v); db.yieldIfContendedSafely(); if (id != -1) { res++; } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } String notify; if (res != 0 && ((notify = uri.getQueryParameter(QUERY_NOTIFY)) == null || "true".equals(notify))) { getContext().getContentResolver().notifyChange(uri, null); } return res; }
@Override public int bulkInsert(Uri uri, ContentValues[] values) { // Resolve the URI. int match = mUriMatcher.match(uri); Mapping mapping = match != UriMatcher.NO_MATCH ? mMappings.get(match) : null; if (mapping == null || mapping.hasId) { throw new IllegalArgumentException("Invalid URI: " + uri); } // Insert all rows into the database and notify observers. String tableName = mapping.table.getTableName(); SQLiteDatabase database = mDatabase.getWritableDatabase(); int numInserted = 0; try { int length = values.length; database.beginTransaction(); for (int i = 0; i != length; ++i) { database.insert(tableName, NULL_COLUMN_HACK, values[i]); } database.setTransactionSuccessful(); numInserted = length; } finally { database.endTransaction(); } notifyChange(uri); return numInserted; }
@Override public synchronized void close() { if (db != null) db.close(); super.close(); }
// 设置ListView protected void setListData(String date) { itemAccess = new ItemTableAccess(sqlHelper.getReadableDatabase()); list = itemAccess.findAnalyzeJieHuanDetail(date); itemAccess.close(); adapter = new SimpleAdapter( this, list, R.layout.list_analyzejiehuan, new String[] { "itembuydate", "jiechuprice", "huanruprice", "jieruprice", "huanchuprice" }, new int[] { R.id.tv_analyze_itembuydate, R.id.tv_analyze_jiechu, R.id.tv_analyze_huanru, R.id.tv_analyze_jieru, R.id.tv_analyze_huanchu }); listAnalyzeJieHuanDetail.setAdapter(adapter); // 设置empty if (list.size() == 0) { layNoItem.setVisibility(View.VISIBLE); } else { layNoItem.setVisibility(View.GONE); } }
@Override public int delete(Uri uri, String selection, String[] selectionArgs) { int count = 0; boolean applyingBatch = applyingBatch(); if (!applyingBatch) { mDb = mOpenHelper.getWritableDatabase(); mDb.beginTransactionWithListener(this); try { count = deleteInTransaction(uri, selection, selectionArgs); if (count > 0) { mNotifyChange = true; } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } onEndTransaction(); } else { count = deleteInTransaction(uri, selection, selectionArgs); if (count > 0) { mNotifyChange = true; } } return count; }
/** * Write data to the database in a transaction NOTE: Should only be called by one thread at a time * (the writeThread) * * @param datum */ private void writeToDatabase(String databaseName, Intent intent) { Log.i(LogUtil.TAG, "Writing to database"); SQLiteOpenHelper dbHelper = getOrCreateDatabaseHelper(databaseName); SQLiteDatabase db = dbHelper.getWritableDatabase(); try { db.beginTransaction(); updateDatabase(db, intent); db.setTransactionSuccessful(); Log.i(LogUtil.TAG, "Writing successful"); } catch (Exception e) { Log.e(LogUtil.TAG, "DataBaseService: save error", e); } finally { db.endTransaction(); } db.close(); }
@Override public Uri insert(Uri uri, ContentValues values) { Uri result = null; boolean applyingBatch = applyingBatch(); if (!applyingBatch) { mDb = mOpenHelper.getWritableDatabase(); mDb.beginTransactionWithListener(this); try { result = insertInTransaction(uri, values); if (result != null) { mNotifyChange = true; } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } onEndTransaction(); } else { result = insertInTransaction(uri, values); if (result != null) { mNotifyChange = true; } } return result; }
@Override public void onOpen(SQLiteDatabase db) { super.onOpen(db); if (!db.isReadOnly()) { db.execSQL("PRAGMA foreign_keys=ON;"); } }
@Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { int count = 0; SQLiteDatabase db = openHelper.getWritableDatabase(); int match = uriMatcher.match(uri); switch (match) { case CHATS: count = db.update(TABLE_CHAT, values, where, whereArgs); break; case MESSAGES: count = db.update(TABLE_MESSAGE, values, where, whereArgs); break; case CHAT_ID: count = db.update( TABLE_CHAT, values, ChatData.KEY_ID + "=" + Integer.parseInt(uri.getPathSegments().get(1)), null); break; case MESSAGE_ID: count = db.update( TABLE_MESSAGE, values, MessageData.KEY_ID + "=" + Integer.parseInt(uri.getPathSegments().get(1)), null); break; default: throw new UnsupportedOperationException("Cannot update URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; }
@Override public Cursor query( Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // Resolve the URI. int match = mUriMatcher.match(uri); if (match == UriMatcher.NO_MATCH) { throw new IllegalArgumentException("Invalid URI: " + uri); } // Add the ID predicate if needed. Mapping mapping = mMappings.get(match); if (mapping.hasId) { selection = whereWithId(uri, selection); } // System.out.println("QUERY " + uri + " WHERE (" + selection + ")"); // Run the query. String tableName = mapping.table.getTableName(); Cursor cursor = mDatabase .getReadableDatabase() .query(tableName, projection, selection, selectionArgs, null, null, sortOrder); cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; }
public static SQLiteDatabase open(Context context) { SQLiteOpenHelper helper = new SQLiteOpenHelper(context, "messages.sqlite", null, 1) { @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {} @Override public void onCreate(SQLiteDatabase db) { db.execSQL( "CREATE TABLE sms (key TEXT PRIMARY KEY NOT NULL, number TEXT NOT NULL, date INTEGER NOT NULL, message TEXT, type TEXT NOT NULL, image TEXT, unread INTEGER)"); } }; return helper.getWritableDatabase(); }
@Override public synchronized void close() { if (myDataBase != null) myDataBase.close(); super.close(); }
@Override public Uri insert(Uri uri, ContentValues values) { Log.i(TAG, "insert " + TAG); SQLiteDatabase db = mDbHelper.getWritableDatabase(); Long id = db.insert(Contacto.TABLE_NAME, null, values); return Uri.parse(Contacto.URI + "/" + id.toString()); }
@Override public synchronized void close() { if (this.database != null) { this.database.close(); } super.close(); }
public ProfileResultAdapter(Context context) { ViewInspector.runtimeComponentMap .get(((ContextThemeWrapper) context).getBaseContext()) .inject(this); mLayoutInflater = LayoutInflater.from(context); String avgsql = "select avg(" + ViewProfile.MEASURE_DURATION + "), " + "avg(" + ViewProfile.LAYOUT_DURATION + "), " + "avg(" + ViewProfile.DRAW_DURATION + ") " + "from " + ViewProfile.TABLE; Cursor cursor = db.getReadableDatabase().rawQuery(avgsql, null); cursor.moveToNext(); mAvgMeasure = cursor.getLong(0) / 1000.0; mAvgLayout = cursor.getLong(1) / 1000.0; mAvgDraw = cursor.getLong(2) / 1000.0; cursor.close(); }