List of usage examples for android.content ContentResolver query
public final @Nullable Cursor query(@RequiresPermission.Read @NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder)
From source file:com.android.providers.contacts.ContactsSyncAdapter.java
private static void addGroupMembershipToContactEntry(String account, ContentResolver cr, long personId, ContactEntry entry) throws ParseException { Cursor c = cr.query(GroupMembership.RAW_CONTENT_URI, null, "person=" + personId, null, null); try {//from w ww. j av a 2 s . co m int serverIdIndex = c.getColumnIndexOrThrow(GroupMembership.GROUP_SYNC_ID); int localIdIndex = c.getColumnIndexOrThrow(GroupMembership.GROUP_ID); while (c.moveToNext()) { String serverId = c.getString(serverIdIndex); if (serverId == null) { final Uri groupUri = ContentUris.withAppendedId(Groups.CONTENT_URI, c.getLong(localIdIndex)); Cursor groupCursor = cr.query(groupUri, new String[] { Groups._SYNC_ID }, null, null, null); try { if (groupCursor.moveToNext()) { serverId = groupCursor.getString(0); } } finally { groupCursor.close(); } } if (serverId == null) { // the group hasn't been synced yet, we can't complete this operation since // we don't know what server id to use for the group throw new ParseException("unable to construct GroupMembershipInfo since the " + "group _sync_id isn't known yet, will retry later"); } GroupMembershipInfo groupMembershipInfo = new GroupMembershipInfo(); String groupId = getCanonicalGroupsFeedForAccount(account) + "/" + serverId; groupMembershipInfo.setGroup(groupId); groupMembershipInfo.setDeleted(false); entry.addGroup(groupMembershipInfo); } } finally { if (c != null) c.close(); } }
From source file:com.bilibili.boxing.model.task.impl.AlbumTask.java
private void buildAlbumInfo(ContentResolver cr) { String[] distinctBucketColumns = new String[] { Media.BUCKET_ID, Media.BUCKET_DISPLAY_NAME }; Cursor bucketCursor = null;/*from w w w . ja v a 2 s. c o m*/ try { bucketCursor = cr.query(Media.EXTERNAL_CONTENT_URI, distinctBucketColumns, "0==0)" + " GROUP BY(" + Media.BUCKET_ID, null, Media.DATE_MODIFIED + " desc"); if (bucketCursor != null && bucketCursor.moveToFirst()) { do { String buckId = bucketCursor.getString(bucketCursor.getColumnIndex(Media.BUCKET_ID)); String name = bucketCursor.getString(bucketCursor.getColumnIndex(Media.BUCKET_DISPLAY_NAME)); AlbumEntity album = buildAlbumInfo(name, buckId); if (!TextUtils.isEmpty(buckId)) { buildAlbumCover(cr, buckId, album); } } while (bucketCursor.moveToNext() && !bucketCursor.isLast()); } } finally { if (bucketCursor != null) { bucketCursor.close(); } } }
From source file:com.android.calendar.event.EventLocationAdapter.java
/** * Matches the input string against recent locations. *//*from w w w.j ava 2 s . c om*/ private static List<Result> queryRecentLocations(ContentResolver resolver, String input, Context context) { // TODO: also match each word in the address? String filter = input == null ? "" : input + "%"; if (filter.isEmpty()) { return null; } if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) { //If permission is not granted then just return. Log.d(TAG, "Manifest.permission.READ_CALENDAR is not granted"); return null; } // Query all locations prefixed with the constraint. There is no way to insert // 'DISTINCT' or 'GROUP BY' to get rid of dupes, so use post-processing to // remove dupes. We will order query results by descending event ID to show // results that were most recently inputed. Cursor c = resolver.query(Events.CONTENT_URI, EVENT_PROJECTION, LOCATION_WHERE, new String[] { "1", filter }, Events._ID + " DESC"); try { List<Result> recentLocations = null; if (c != null) { // Post process query results. recentLocations = processLocationsQueryResults(c); } return recentLocations; } finally { if (c != null) { c.close(); } } }
From source file:com.android.providers.contacts.ContactsSyncAdapter.java
static private void addContactMethodsToContactEntry(ContentResolver cr, long personId, ContactEntry entry) throws ParseException { Cursor c = cr.query(ContactMethods.CONTENT_URI, null, "person=" + personId, null, null); int kindIndex = c.getColumnIndexOrThrow(ContactMethods.KIND); int dataIndex = c.getColumnIndexOrThrow(ContactMethods.DATA); int auxDataIndex = c.getColumnIndexOrThrow(ContactMethods.AUX_DATA); try {/*from ww w .j a va 2 s. c o m*/ while (c.moveToNext()) { int kind = c.getInt(kindIndex); switch (kind) { case Contacts.KIND_IM: { ImAddress address = new ImAddress(); cursorToContactsElement(address, c, PROVIDER_TYPE_TO_ENTRY_IM); address.setAddress(c.getString(dataIndex)); Object object = ContactMethods.decodeImProtocol(c.getString(auxDataIndex)); if (object == null) { address.setProtocolPredefined(ImAddress.PROTOCOL_NONE); } else if (object instanceof Integer) { address.setProtocolPredefined(PROVIDER_IM_PROTOCOL_TO_ENTRY_PROTOCOL.get((Integer) object)); } else { if (!(object instanceof String)) { throw new IllegalArgumentException("expected an String, " + object); } address.setProtocolPredefined(ImAddress.PROTOCOL_CUSTOM); address.setProtocolCustom((String) object); } entry.addImAddress(address); break; } case Contacts.KIND_POSTAL: { PostalAddress address = new PostalAddress(); cursorToContactsElement(address, c, PROVIDER_TYPE_TO_ENTRY_POSTAL); address.setValue(c.getString(dataIndex)); entry.addPostalAddress(address); break; } case Contacts.KIND_EMAIL: { EmailAddress address = new EmailAddress(); cursorToContactsElement(address, c, PROVIDER_TYPE_TO_ENTRY_EMAIL); address.setAddress(c.getString(dataIndex)); entry.addEmailAddress(address); break; } } } } finally { if (c != null) c.close(); } }
From source file:ca.zadrox.dota2esportticker.service.ReminderAlarmService.java
private void notifyMatch(long matchId) { if (!PrefUtils.shouldShowMatchReminders(this)) { return;//from w ww . j a va2 s.c o m } final ContentResolver cr = getContentResolver(); Cursor c = cr.query(MatchContract.SeriesEntry.CONTENT_URI, MatchDetailQuery.PROJECTION, SESSION_ID_WHERE_CLAUSE, new String[] { String.valueOf(matchId) }, null); if (!c.moveToNext()) { return; } Intent baseIntent = new Intent(this, MatchActivity.class); baseIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); TaskStackBuilder taskBuilder = TaskStackBuilder.create(this).addNextIntent(baseIntent); Intent matchIntent = new Intent(this, MatchDetailActivity.class); matchIntent.putExtra(MatchDetailActivity.ARGS_GG_MATCH_ID, matchId); taskBuilder.addNextIntent(matchIntent); PendingIntent pi = taskBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT); final Resources res = getResources(); String contentTitle = c.getString(MatchDetailQuery.TEAM_ONE_NAME) + " vs " + c.getString(MatchDetailQuery.TEAM_TWO_NAME); String contentText; long currentTime = TimeUtils.getUTCTime(); long matchStart = c.getLong(MatchDetailQuery.DATE_TIME); int minutesLeft = (int) (matchStart - currentTime + 59000) / 60000; if (minutesLeft < 2 && minutesLeft >= 0) { minutesLeft = 1; } if (minutesLeft < 0) { contentText = "is scheduled to start now. (" + c.getString(MatchDetailQuery.TOURNAMENT_NAME) + ")"; } else { contentText = "is scheduled to start in " + minutesLeft + " min. (" + c.getString(MatchDetailQuery.TOURNAMENT_NAME) + ")"; } NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this).setContentTitle(contentTitle) .setContentText(contentText).setColor(res.getColor(R.color.theme_primary)) .setTicker(contentTitle + " is about to start.") .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE) .setLights(NOTIFICATION_ARGB_COLOR, NOTIFICATION_LED_ON_MS, NOTIFICATION_LED_OFF_MS) .setSmallIcon(R.drawable.ic_notification).setContentIntent(pi) .setPriority(Notification.PRIORITY_DEFAULT).setAutoCancel(true); NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(NOTIFICATION_ID, notifBuilder.build()); }
From source file:com.todoroo.astrid.gcal.GCalControlSet.java
private void viewCalendarEvent() { if (calendarUri == null) { return;/*from ww w .jav a 2 s . c om*/ } ContentResolver cr = activity.getContentResolver(); Intent intent = new Intent(Intent.ACTION_EDIT, calendarUri); Cursor cursor = cr.query(calendarUri, new String[] { "dtstart", "dtend" }, null, null, null); try { if (cursor.getCount() == 0) { // event no longer exists, recreate it calendarUri = null; writeToModel(model); return; } cursor.moveToFirst(); intent.putExtra("beginTime", cursor.getLong(0)); intent.putExtra("endTime", cursor.getLong(1)); } catch (Exception e) { log.error(e.getMessage(), e); Toast.makeText(activity, R.string.gcal_TEA_error, Toast.LENGTH_LONG).show(); } finally { cursor.close(); } activity.startActivity(intent); }
From source file:com.prashantpal.sunshine.app.FetchWeatherTask.java
/** * Helper method to handle insertion of a new location in the weather database. * * @param locationSetting The location string used to request updates from the server. * @param cityName A human-readable city name, e.g "Mountain View" * @param lat the latitude of the city//from w w w.j a v a2s. com * @param lon the longitude of the city * @return the row ID of the added location. */ long addLocation(String locationSetting, String cityName, double lat, double lon) { // Students: First, check if the location with this city name exists in the db // If it exists, return the current ID long locationId; ContentResolver resolver = mContext.getContentResolver(); Cursor cursor = resolver.query(WeatherContract.LocationEntry.CONTENT_URI, new String[] { WeatherContract.LocationEntry._ID }, WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + "= ?", new String[] { locationSetting }, null); if (cursor.moveToFirst()) { int locationIdIndex = cursor.getColumnIndex(WeatherContract.LocationEntry._ID); locationId = cursor.getLong(locationIdIndex); } else { ContentValues contentValues = new ContentValues(); contentValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName); contentValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat); contentValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon); contentValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting); Uri uri = resolver.insert(WeatherContract.LocationEntry.CONTENT_URI, contentValues); locationId = ContentUris.parseId(uri); } cursor.close(); // Otherwise, insert it using the content resolver and the base URI return locationId; }
From source file:com.tcm.sunshine.app.FetchWeatherTask.java
/** * Helper method to handle insertion of a new location in the weather database. * * @param locationSetting The location string used to request updates from the server. * @param cityName A human-readable city name, e.g "Mountain View" * @param lat the latitude of the city/*from www . j ava2 s .c o m*/ * @param lon the longitude of the city * @return the row ID of the added location. */ long addLocation(String locationSetting, String cityName, double lat, double lon) { // Students: First, check if the location with this city name exists in the db // If it exists, return the current ID // Otherwise, insert it using the content resolver and the base URI ContentResolver contentResolver = mContext.getContentResolver(); Cursor cursor = contentResolver.query(LocationEntry.CONTENT_URI, new String[] { LocationEntry._ID }, LocationEntry.COLUMN_CITY_NAME + " = ?", new String[] { cityName }, null); try { if (cursor.moveToFirst()) { return cursor.getInt(cursor.getColumnIndex(LocationEntry._ID)); } } finally { cursor.close(); } ContentValues contentValues = new ContentValues(); contentValues.put(LocationEntry.COLUMN_LOCATION_SETTING, locationSetting); contentValues.put(LocationEntry.COLUMN_CITY_NAME, cityName); contentValues.put(LocationEntry.COLUMN_COORD_LAT, lat); contentValues.put(LocationEntry.COLUMN_COORD_LONG, lon); Uri insertUri = contentResolver.insert(LocationEntry.CONTENT_URI, contentValues); return ContentUris.parseId(insertUri); }
From source file:com.marvin.rocklock.navigation.ColumnGroupedSongPicker.java
@Override public LinkedHashMap<Integer, String> getSearchResults(Context context, String search) { ContentResolver resolver = context.getContentResolver(); search.replace("'", "''"); String[] proj = { mProjection[TRACK_ID], mProjection[mGroupColumn] }; String filter = mProjection[mGroupColumn] + " LIKE '" + search + "%'"; Cursor query = resolver.query(mSearchUri, proj, filter, null, null); LinkedHashMap<Integer, String> results = null; if (query != null && query.moveToFirst()) { results = new LinkedHashMap<Integer, String>(); do {//from ww w. j a v a 2 s.c o m results.put(query.getInt(0), query.getString(1)); } while (query.moveToNext()); } if (query != null) { query.close(); } return results; }
From source file:com.yohpapa.research.simplemusicplayer.plugins.ListManager.java
/** * @see CordovaPlugin/*from w ww . j a va 2 s. co m*/ * @param action * @param args * @param callbackContext * @return * @throws JSONException */ @Override public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { if ("get_album_info".equals(action)) { final Context context = cordova.getActivity().getApplicationContext(); cordova.getThreadPool().execute(new Runnable() { @Override public void run() { ContentResolver resolver = context.getContentResolver(); Cursor cursor = null; try { cursor = resolver.query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM, MediaStore.Audio.Albums.NUMBER_OF_SONGS, MediaStore.Audio.Albums.ARTIST, MediaStore.Audio.Albums.ALBUM_ART, }, null, null, MediaStore.Audio.Albums.ALBUM + " ASC"); if (cursor == null || !cursor.moveToFirst()) { callbackContext.error("The cursor is invalid."); return; } JSONArray results = new JSONArray(); do { JSONObject obj = new JSONObject(); obj.put("id", CursorHelper.getLong(cursor, MediaStore.Audio.Albums._ID)); obj.put("name", CursorHelper.getString(cursor, MediaStore.Audio.Albums.ALBUM)); obj.put("numTracks", CursorHelper.getInt(cursor, MediaStore.Audio.Albums.NUMBER_OF_SONGS)); obj.put("artist", CursorHelper.getString(cursor, MediaStore.Audio.Albums.ARTIST)); obj.put("artwork", CursorHelper.getString(cursor, MediaStore.Audio.Albums.ALBUM_ART)); results.put(obj); } while (cursor.moveToNext()); callbackContext.success(results); } catch (JSONException e) { callbackContext.error(e.toString()); } finally { if (cursor != null) { cursor.close(); } } } }); return true; } else if ("get_track_info".equals(action)) { final long albumId = args.getLong(0); final Context context = cordova.getActivity().getApplicationContext(); cordova.getThreadPool().execute(new Runnable() { @Override public void run() { ContentResolver resolver = context.getContentResolver(); Cursor albumCursor = null; Cursor trackCursor = null; try { albumCursor = resolver.query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Audio.Albums.ALBUM, MediaStore.Audio.Albums.ALBUM_ART, }, MediaStore.Audio.Albums._ID + "=?", new String[] { String.valueOf(albumId) }, null); if (albumCursor == null || !albumCursor.moveToFirst() || albumCursor.getCount() != 1) { callbackContext.error("The album's cursor is invalid."); return; } trackCursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.DURATION, }, MediaStore.Audio.Media.ALBUM_ID + "=?", new String[] { String.valueOf(albumId) }, MediaStore.Audio.Media.TRACK + " ASC"); if (trackCursor == null || !trackCursor.moveToFirst()) { callbackContext.error("The cursor is invalid."); return; } JSONObject result = new JSONObject(); result.put("album", CursorHelper.getString(albumCursor, MediaStore.Audio.Albums.ALBUM)); result.put("artwork", CursorHelper.getString(albumCursor, MediaStore.Audio.Albums.ALBUM_ART)); JSONArray tracks = new JSONArray(); do { JSONObject obj = new JSONObject(); obj.put("id", CursorHelper.getLong(trackCursor, MediaStore.Audio.Media._ID)); obj.put("title", CursorHelper.getString(trackCursor, MediaStore.Audio.Media.TITLE)); obj.put("artist", CursorHelper.getString(trackCursor, MediaStore.Audio.Media.ARTIST)); obj.put("duration", CursorHelper.getLong(trackCursor, MediaStore.Audio.Media.DURATION)); tracks.put(obj); } while (trackCursor.moveToNext()); result.put("tracks", tracks); callbackContext.success(result); } catch (JSONException e) { callbackContext.error(e.toString()); } finally { if (albumCursor != null) { albumCursor.close(); } if (trackCursor != null) { trackCursor.close(); } } } }); return true; } return false; }