List of usage examples for android.database.sqlite SQLiteDatabase query
public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy,
String having, String orderBy)
From source file:com.raspi.chatapp.util.storage.MessageHistory.java
public String getName(String buddyId) { int index = buddyId.indexOf('@'); if (index > -1) buddyId = buddyId.substring(0, index); SQLiteDatabase db = mDbHelper.getReadableDatabase(); String where = MessageHistoryContract.ChatEntry.COLUMN_NAME_BUDDY_ID + "=?"; Cursor c = db.query(MessageHistoryContract.ChatEntry.TABLE_NAME_ALL_CHATS, new String[] { MessageHistoryContract.ChatEntry.COLUMN_NAME_NAME }, where, new String[] { buddyId }, null, null, null);/* www. ja va 2 s .co m*/ c.moveToFirst(); String result = null; if (c.getCount() >= 1) { try { result = c.getString(0); } catch (Exception e) { result = buddyId; } } db.close(); c.close(); // Log.d("MH_DEBUG", result); return result; }
From source file:org.y20k.transistor.core.Station.java
public static void AddStationItemToDb(Station stationItem, Activity mActivity) { //db test/*from w w w .j av a2 s. c om*/ StationsDbHelper mDbHelper = new StationsDbHelper(mActivity); // Gets the data repository in write mode SQLiteDatabase db = mDbHelper.getWritableDatabase(); // Filter results WHERE "title" = 'My Title' String selection = StationsDbContract.StationEntry.COLUMN_UNIQUE_ID + " = ?"; String[] selectionArgs = { stationItem.UNIQUE_ID }; String[] projection = { StationsDbContract.StationEntry._ID, StationsDbContract.StationEntry.COLUMN_UNIQUE_ID }; String sortOrder = StationsDbContract.StationEntry.COLUMN_UNIQUE_ID + " DESC"; Cursor cursor = db.query(StationsDbContract.StationEntry.TABLE_NAME, // The table to query projection, // The columns to return selection, // The columns for the WHERE clause selectionArgs, // The values for the WHERE clause null, // don't group the rows null, // don't filter by row groups sortOrder); if (cursor.getCount() == 0) { //record not found // Create a new map of values, where column names are the keys ContentValues values = new ContentValues(); values.put(StationsDbContract.StationEntry.COLUMN_NAME_TITLE, stationItem.TITLE); values.put(StationsDbContract.StationEntry.COLUMN_UNIQUE_ID, stationItem.UNIQUE_ID); values.put(StationsDbContract.StationEntry.COLUMN_NAME_SUBTITLE, stationItem.SUBTITLE); values.put(StationsDbContract.StationEntry.COLUMN_DESCRIPTION, stationItem.DESCRIPTION); values.put(StationsDbContract.StationEntry.COLUMN_IMAGE_PATH, stationItem.IMAGE_PATH); values.put(StationsDbContract.StationEntry.COLUMN_IMAGE_FILE_NAME, stationItem.IMAGE_FILE_NAME); values.put(StationsDbContract.StationEntry.COLUMN_SMALL_IMAGE_FILE_NAME, stationItem.SMALL_IMAGE_FILE_NAME); values.put(StationsDbContract.StationEntry.COLUMN_URI, stationItem.StreamURI); values.put(StationsDbContract.StationEntry.COLUMN_CONTENT_TYPE, stationItem.CONTENT_TYPE); values.put(StationsDbContract.StationEntry.COLUMN_RATING, stationItem.RATING); values.put(StationsDbContract.StationEntry.COLUMN_IS_FAVOURITE, 0); //default values.put(StationsDbContract.StationEntry.COLUMN_COMMA_SEPARATED_TAGS, stationItem.COMMA_SEPARATED_TAGS); values.put(StationsDbContract.StationEntry.COLUMN_CATEGORY, stationItem.CATEGORY); values.put(StationsDbContract.StationEntry.COLUMN_MARKDOWN_DESCRIPTION, stationItem.MarkdownDescription); values.put(StationsDbContract.StationEntry.COLUMN_SMALL_IMAGE_URL, stationItem.SMALL_IMAGE_PATH); // Insert the new row, returning the primary key value of the new row long newRowId = db.insert(StationsDbContract.StationEntry.TABLE_NAME, null, values); stationItem._ID = newRowId; } //todo: , else then update the existing with new data db.close(); }
From source file:com.apps.howard.vicissitude.classes.tasks.FetchLogDataTask.java
protected Cursor doInBackground(Void... params) { AlertLogDbHelper dbHelper = new AlertLogDbHelper(activity.getActivity()); SQLiteDatabase db = dbHelper.getReadableDatabase(); // Define a projection that specifies which columns from the database // you will actually use after this query. String[] projection = { AlertLogContract.AlertLogEntry.COLUMN_NAME_SERVICE, AlertLogContract.AlertLogEntry.COLUMN_NAME_ACTION, AlertLogContract.AlertLogEntry.COLUMN_NAME_ADDED, "_id" }; // How you want the results sorted in the resulting Cursor String sortOrder = AlertLogContract.AlertLogEntry.COLUMN_NAME_ADDED + " DESC"; return db.query(AlertLogContract.AlertLogEntry.TABLE_NAME, // The table to query projection, // The columns to return null, null, null, // don't group the rows null, // don't filter by row groups sortOrder // The sort order );//w w w . j av a 2 s . co m }
From source file:com.nonninz.robomodel.RoboModel.java
@SuppressLint("DefaultLocale") public void reload() throws InstanceNotFoundException { if (!isSaved()) { throw new IllegalStateException("This instance has not yet been saved."); }//from w ww .j av a2 s .com // Retrieve current entry in the database SQLiteDatabase db = mDatabaseManager.openOrCreateDatabase(getDatabaseName()); Cursor query; /* * Try to query the table. If the Table doesn't exist, fix the DB and re-run the query. */ try { query = db.query(getTableName(), null, where(mId), null, null, null, null); } catch (final SQLiteException e) { mDatabaseManager.createOrPopulateTable(mTableName, getSavedFields(), db); query = db.query(getTableName(), null, where(mId), null, null, null, null); } if (query.moveToFirst()) { try { setFieldsWithQueryResult(query); } catch (DatabaseNotUpToDateException e) { Ln.w(e, "Updating table %s", mTableName); query.close(); // Update table with new columns mDatabaseManager.createOrPopulateTable(mTableName, getSavedFields(), db); mDatabaseManager.closeDatabase(); db = mDatabaseManager.openOrCreateDatabase(getDatabaseName()); // Retry try { query = db.query(getTableName(), null, where(mId), null, null, null, null); query.moveToFirst(); setFieldsWithQueryResult(query); } catch (DatabaseNotUpToDateException ee) { throw new RuntimeException("Could not repair database.", ee); } } query.close(); } else { query.close(); final String msg = String.format("No entry in database with id %d for model %s", getId(), getTableName()); throw new InstanceNotFoundException(msg); } }
From source file:syncthing.android.settings.AppSettings.java
public void saveCredentials(Credentials creds) { SQLiteDatabase _db = db.getWritableDatabase(); Cursor c = null;//from www . j a va2 s .c o m try { ContentValues cv = new ContentValues(); cv.put(CredentialsDB.SCHEMA.ALIAS, creds.alias); cv.put(CredentialsDB.SCHEMA.URL, creds.url); cv.put(CredentialsDB.SCHEMA.API_KEY, creds.apiKey); cv.put(CredentialsDB.SCHEMA.CERT, creds.caCert); String[] sel = new String[] { creds.id }; _db.beginTransaction(); c = _db.query(CredentialsDB.SCHEMA.TABLE, idCols, credentialsDeviceIdSel, sel, null, null, null); if (c != null && c.getCount() > 0) { _db.update(CredentialsDB.SCHEMA.TABLE, cv, credentialsDeviceIdSel, sel); } else { cv.put(CredentialsDB.SCHEMA.DEVICE_ID, creds.id); _db.insert(CredentialsDB.SCHEMA.TABLE, null, cv); } _db.setTransactionSuccessful(); } finally { _db.endTransaction(); if (c != null) c.close(); } }
From source file:org.pixmob.freemobile.netstat.SyncServiceTesting.java
private String getDeviceId() { final SQLiteDatabase db = dbHelper.getWritableDatabase(); String deviceId = null;// ww w . ja v a 2 s .co m Cursor deviceCursor = null; try { deviceCursor = db.query("device_testing", new String[] { "device_id" }, null, null, null, null, null); if (deviceCursor.moveToNext()) { deviceId = deviceCursor.getString(0); } } catch (Exception e) { Log.e(TAG, Log.getStackTraceString(e)); } finally { try { if (deviceCursor != null) deviceCursor.close(); } catch (Exception e) { Log.e(TAG, Log.getStackTraceString(e)); } } if (deviceId == null) { // Generate a new device identifier. deviceId = UUID.randomUUID().toString(); // Store this device identifier in the database. final ContentValues cv = new ContentValues(1); cv.put("device_id", deviceId); db.insertOrThrow("device_testing", null, cv); } return deviceId; }
From source file:pl.selvin.android.syncframework.content.TableInfo.java
public void GetChanges(SQLiteDatabase db, JsonGenerator gen, ArrayList<TableInfo> notifyTableInfo) throws IOException { String[] cols = new String[columns.length + 3]; int i = 0;//from www .j ava2 s .c om for (; i < columns.length; i++) cols[i] = columns[i].name; cols[i] = _.uri; cols[i + 1] = _.tempId; cols[i + 2] = _.isDeleted; Cursor c = db.query(name, cols, _.isDirtyP, new String[] { "1" }, null, null, null); //to fix startPos > actual rows for large cursors db operations should be done after cursor is closed ... final ArrayList<OperationHolder> operations = new ArrayList<OperationHolder>(); if (c.moveToFirst()) { if (!notifyTableInfo.contains(this)) notifyTableInfo.add(this); do { gen.writeStartObject(); gen.writeObjectFieldStart(_.__metadata); gen.writeBooleanField(_.isDirty, true); gen.writeStringField(_.type, scope_name); //Log.d("before", scope_name + ":" + c.getLong(i + 3)); String uri = c.getString(i); //Log.d("after", scope_name + ":" + c.getLong(i + 3)); if (uri == null) { gen.writeStringField(_.tempId, c.getString(i + 1)); } else { gen.writeStringField(_.uri, uri); final ContentValues update = new ContentValues(1); update.put(_.isDirty, 0); operations.add(new OperationHolder(name, OperationHolder.UPDATE, update, uri)); } boolean isDeleted = c.getInt(i + 2) == 1; if (isDeleted) { gen.writeBooleanField(_.isDeleted, true); gen.writeEndObject();// meta operations.add(new OperationHolder(name, OperationHolder.DELETE, null, uri)); } else { gen.writeEndObject();// meta for (i = 0; i < columns.length; i++) { if (columns[i].nullable && c.isNull(i)) { gen.writeNullField(columns[i].name); } else { switch (columns[i].type) { case ColumnType.BLOB: gen.writeBinaryField(columns[i].name, c.getBlob(i)); break; case ColumnType.BOOLEAN: gen.writeBooleanField(columns[i].name, c.getLong(i) == 1); break; case ColumnType.INTEGER: gen.writeNumberField(columns[i].name, c.getLong(i)); break; case ColumnType.DATETIME: try { gen.writeStringField(columns[i].name, String.format(msdate, sdf.parse(c.getString(i)).getTime())); } catch (Exception e) { if (BuildConfig.DEBUG) { Log.e("ListSync", e.getLocalizedMessage()); } } break; case ColumnType.NUMERIC: gen.writeNumberField(columns[i].name, c.getDouble(i)); break; default: gen.writeStringField(columns[i].name, c.getString(i)); break; } } } } gen.writeEndObject(); // end of row } while (c.moveToNext()); } c.close(); for (OperationHolder operation : operations) operation.execute(db); }
From source file:info.staticfree.android.units.UnitUsageDBHelper.java
public int getUnitUsageDbCount() { final SQLiteDatabase db = getReadableDatabase(); final String[] proj = { UsageEntry._ID }; if (!db.isOpen()) { return -1; }/*w w w . j a va2 s . co m*/ final Cursor c = db.query(DB_USAGE_TABLE, proj, null, null, null, null, null); c.moveToFirst(); final int count = c.getCount(); c.close(); db.close(); return count; }
From source file:com.jefftharris.passwdsafe.NotificationMgr.java
/** Load the expiration entries for a URI from the database */ private TreeSet<ExpiryEntry> loadUriEntries(final long uriId, final long expiration, final LongReference nextExpiration, final SQLiteDatabase db) throws SQLException { TreeSet<ExpiryEntry> expired = new TreeSet<>(); Cursor cursor = db.query(DB_TABLE_EXPIRYS, new String[] { DB_COL_EXPIRYS_UUID, DB_COL_EXPIRYS_TITLE, DB_COL_EXPIRYS_GROUP, DB_COL_EXPIRYS_EXPIRE }, DB_MATCH_EXPIRYS_URI, new String[] { Long.toString(uriId) }, null, null, null); try {/* ww w . j a v a2 s. c om*/ while (cursor.moveToNext()) { long expiry = cursor.getLong(3); if (expiry <= expiration) { ExpiryEntry entry = new ExpiryEntry(cursor.getString(0), cursor.getString(1), cursor.getString(2), expiry); PasswdSafeUtil.dbginfo(TAG, "expired entry: %s/%s, at: %tc", entry.itsGroup, entry.itsTitle, entry.itsExpiry); expired.add(entry); } else if (expiry < nextExpiration.itsValue) { nextExpiration.itsValue = expiry; } } } finally { cursor.close(); } return expired; }