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.example.mydemos.view.RingtonePickerActivity.java
private void setDefaultRingtone() { final Uri musicDefault = MediaStore.Audio.Media.INTERNAL_CONTENT_URI; final String musicTitle = MediaStore.Audio.AudioColumns.TITLE; final String musicId = MediaStore.Audio.Media._ID; final String musicName = MediaStore.Audio.AudioColumns.DISPLAY_NAME; // Get a ContentResovler, // so that we can read the music information form SD card. ContentResolver contentResolver = getContentResolver(); Uri uri = null;/*from w ww . ja v a 2s. c o m*/ String ringtone = "AA_Preo_ringtone.ogg"; Cursor cursor = contentResolver.query(musicDefault, new String[] { musicId, musicName }, musicName + " LIKE ?", new String[] { ringtone }, null); // If cursor has a recode, we support that we find the music. if (cursor.moveToNext()) { // Get the music id. int position = cursor.getInt(cursor.getColumnIndex(musicId)); uri = Uri.withAppendedPath(musicDefault, "/" + position); Log.d("test", uri.toString()); } // Finish our query work. cursor.close(); if (uri != null) { ContentValues values = new ContentValues(); values.put(MediaStore.Audio.AudioColumns.ALBUM_ARTIST, "first"); contentResolver.update(uri, values, null, null); } // defaultView = getLayoutInflater().inflate( // R.layout.tab_picker_item, listView, false); // TextView textView = (TextView) defaultView.findViewById(R.id.title); // textView.setText(musicName); // listView.addHeaderView(defaultView, null, true); // mStaticItemCount++; }
From source file:com.android.calendar.alerts.AlertService.java
static boolean updateAlertNotification(Context context) { ContentResolver cr = context.getContentResolver(); NotificationMgr nm = new NotificationMgrWrapper( (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)); final long currentTime = System.currentTimeMillis(); SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context); if (DEBUG) {//from w ww.j ava2 s . c om Log.d(TAG, "Beginning updateAlertNotification"); } 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 false; } if (!prefs.getBoolean(GeneralPreferences.KEY_ALERTS, true)) { if (DEBUG) { Log.d(TAG, "alert preference is OFF"); } // If we shouldn't be showing notifications cancel any existing ones // and return. nm.cancelAll(); return true; } Cursor alertCursor = cr.query(CalendarAlerts.CONTENT_URI, ALERT_PROJECTION, (ACTIVE_ALERTS_SELECTION + currentTime), ACTIVE_ALERTS_SELECTION_ARGS, ACTIVE_ALERTS_SORT); if (alertCursor == null || alertCursor.getCount() == 0) { if (alertCursor != null) { alertCursor.close(); } if (DEBUG) Log.d(TAG, "No fired or scheduled alerts"); nm.cancelAll(); return false; } return generateAlerts(context, nm, AlertUtils.createAlarmManager(context), prefs, alertCursor, currentTime, MAX_NOTIFICATIONS); }
From source file:com.example.android.basicsyncadapter.SyncAdapter.java
/** * Read XML from an input stream, storing it into the content provider. * * <p>This is where incoming data is persisted, committing the results of a sync. In order to * minimize (expensive) disk operations, we compare incoming data with what's already in our * database, and compute a merge. Only changes (insert/update/delete) will result in a database * write.// www . j a va 2 s . c om * * <p>As an additional optimization, we use a batch operation to perform all database writes at * once. * * <p>Merge strategy: * 1. Get cursor to all items in feed<br/> * 2. For each item, check if it's in the incoming data.<br/> * a. YES: Remove from "incoming" list. Check if data has mutated, if so, perform * database UPDATE.<br/> * b. NO: Schedule DELETE from database.<br/> * (At this point, incoming database only contains missing items.)<br/> * 3. For any items remaining in incoming list, ADD to database. */ public void updateLocalFeedData(final InputStream stream, final SyncResult syncResult) throws IOException, XmlPullParserException, RemoteException, OperationApplicationException, ParseException { //final FeedParser feedParser = new FeedParser(); final CAPFeedParser feedParser = new CAPFeedParser(); final ContentResolver contentResolver = getContext().getContentResolver(); //Log.i(TAG, "Parsing stream as Atom feed"); final List<CAPFeedParser.Entry> entries = feedParser.parse(stream); Log.i(TAG, "Parsing complete. Found " + entries.size() + " entries"); ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); // Build hash table of incoming entries HashMap<String, CAPFeedParser.Entry> entryMap = new HashMap<String, CAPFeedParser.Entry>(); for (CAPFeedParser.Entry e : entries) { entryMap.put(e.id, e); } // Get list of all items //Log.i(TAG, "Fetching local entries for merge"); Uri uri = FeedContract.Entry.CONTENT_URI; // Get all entries Cursor c = contentResolver.query(uri, PROJECTION, null, null, null); assert c != null; //Log.i(TAG, "Found " + c.getCount() + " local entries. Computing merge solution..."); // Find stale data int id; String entryId; String title; String description; String headline; String url; String areas; String issued; while (c.moveToNext()) { syncResult.stats.numEntries++; id = c.getInt(COLUMN_ID); entryId = c.getString(COLUMN_ENTRY_ID); title = c.getString(COLUMN_TITLE); description = c.getString(COLUMN_DESCRIPTION); headline = c.getString(COLUMN_HEADLINE); areas = c.getString(COLUMN_AREAS); url = c.getString(COLUMN_LINK); issued = c.getString(COLUMN_ISSUED); CAPFeedParser.Entry match = entryMap.get(entryId); if (match != null) { // Entry exists. Remove from entry map to prevent insert later. entryMap.remove(entryId); // Check to see if the entry needs to be updated Uri existingUri = FeedContract.Entry.CONTENT_URI.buildUpon().appendPath(Integer.toString(id)) .build(); if ((match.title != null && !match.title.equals(title)) || (match.link != null && !match.link.equals(url)) || (match.issued != issued)) { // Update existing record //Log.i(TAG, "Scheduling update: " + existingUri); batch.add(ContentProviderOperation.newUpdate(existingUri) .withValue(FeedContract.Entry.COLUMN_NAME_TITLE, title) .withValue(FeedContract.Entry.COLUMN_NAME_DESCRIPTION, description) .withValue(FeedContract.Entry.COLUMN_NAME_HEADLINE, headline) .withValue(FeedContract.Entry.COLUMN_NAME_ISSUED, issued) .withValue(FeedContract.Entry.COLUMN_NAME_LINK, url) .withValue(FeedContract.Entry.COLUMN_NAME_AREAS, areas).build()); syncResult.stats.numUpdates++; } else { //Log.i(TAG, "No action: " + existingUri); } } else { // Entry doesn't exist. Remove it from the database. Uri deleteUri = FeedContract.Entry.CONTENT_URI.buildUpon().appendPath(Integer.toString(id)).build(); //Log.i(TAG, "Scheduling delete: " + deleteUri); batch.add(ContentProviderOperation.newDelete(deleteUri).build()); syncResult.stats.numDeletes++; } } c.close(); // Add new items for (CAPFeedParser.Entry e : entryMap.values()) { //Log.i(TAG, "Scheduling insert: entry_id=" + e.id); batch.add(ContentProviderOperation.newInsert(FeedContract.Entry.CONTENT_URI) .withValue(FeedContract.Entry.COLUMN_NAME_ENTRY_ID, e.id) .withValue(FeedContract.Entry.COLUMN_NAME_TITLE, e.title) .withValue(FeedContract.Entry.COLUMN_NAME_DESCRIPTION, e.description) .withValue(FeedContract.Entry.COLUMN_NAME_HEADLINE, e.headline) .withValue(FeedContract.Entry.COLUMN_NAME_ISSUED, e.issued) .withValue(FeedContract.Entry.COLUMN_NAME_LINK, e.link) .withValue(FeedContract.Entry.COLUMN_NAME_AREAS, e.areas).build()); syncResult.stats.numInserts++; } //Log.i(TAG, "Merge solution ready. Applying batch update"); mContentResolver.applyBatch(FeedContract.CONTENT_AUTHORITY, batch); mContentResolver.notifyChange(FeedContract.Entry.CONTENT_URI, // URI where data was modified null, // No local observer false); // IMPORTANT: Do not sync to network // This sample doesn't support uploads, but if *your* code does, make sure you set // syncToNetwork=false in the line above to prevent duplicate syncs. }
From source file:cn.edu.wyu.documentviewer.DirectoryResult.java
@Override public final DirectoryResult loadInBackground() { synchronized (this) { if (isLoadInBackgroundCanceled()) { throw new OperationCanceledException(); }/*w w w . ja va 2 s. c o m*/ mSignal = new CancellationSignal(); } final ContentResolver resolver = getContext().getContentResolver(); final String authority = mUri.getAuthority(); final DirectoryResult result = new DirectoryResult(); int userMode = State.MODE_UNKNOWN; // Use default document when searching if (mType == DirectoryFragment.TYPE_SEARCH) { final Uri docUri = DocumentsContract.buildDocumentUri(mRoot.authority, mRoot.documentId); try { mDoc = DocumentInfo.fromUri(resolver, docUri); } catch (FileNotFoundException e) { Log.w(TAG, "Failed to query", e); result.exception = e; return result; } } // Pick up any custom modes requested by user Cursor cursor = null; try { final Uri stateUri = RecentsProvider.buildState(mRoot.authority, mRoot.rootId, mDoc.documentId); cursor = resolver.query(stateUri, null, null, null, null); if (cursor.moveToFirst()) { userMode = getCursorInt(cursor, StateColumns.MODE); } } finally { IOUtils.closeQuietly(cursor); } if (userMode != State.MODE_UNKNOWN) { result.mode = userMode; } else { if ((mDoc.flags & Document.FLAG_DIR_PREFERS_GRID) != 0) { result.mode = State.MODE_GRID; } else { result.mode = State.MODE_LIST; } } if (mUserSortOrder != State.SORT_ORDER_UNKNOWN) { result.sortOrder = mUserSortOrder; } else { if ((mDoc.flags & Document.FLAG_DIR_PREFERS_LAST_MODIFIED) != 0) { result.sortOrder = State.SORT_ORDER_LAST_MODIFIED; } else { result.sortOrder = State.SORT_ORDER_DISPLAY_NAME; } } // Search always uses ranking from provider if (mType == DirectoryFragment.TYPE_SEARCH) { result.sortOrder = State.SORT_ORDER_UNKNOWN; } Log.d(TAG, "userMode=" + userMode + ", userSortOrder=" + mUserSortOrder + " --> mode=" + result.mode + ", sortOrder=" + result.sortOrder); ContentProviderClient client = null; try { client = DocumentsApplication.acquireUnstableProviderOrThrow(resolver, authority); cursor = client.query(mUri, null, null, null, getQuerySortOrder(result.sortOrder), mSignal); cursor.registerContentObserver(mObserver); cursor = new RootCursorWrapper(mUri.getAuthority(), mRoot.rootId, cursor, -1); if (mType == DirectoryFragment.TYPE_SEARCH) { // Filter directories out of search results, for now cursor = new FilteringCursorWrapper(cursor, null, SEARCH_REJECT_MIMES); } else { // Normal directories should have sorting applied cursor = new SortingCursorWrapper(cursor, result.sortOrder); } result.client = client; result.cursor = cursor; } catch (Exception e) { Log.w(TAG, "Failed to query", e); result.exception = e; ContentProviderClient.releaseQuietly(client); } finally { synchronized (this) { mSignal = null; } } return result; }
From source file:com.rjfun.cordova.sms.SMSPlugin.java
protected void createContentObserver() { Activity ctx = this.cordova.getActivity(); this.mObserver = new ContentObserver(new Handler()) { public void onChange(boolean selfChange) { this.onChange(selfChange, null); }/*from ww w . jav a 2 s .c o m*/ public void onChange(boolean selfChange, Uri uri) { ContentResolver resolver = cordova.getActivity().getContentResolver(); Log.d(LOGTAG, ("onChange, selfChange: " + selfChange + ", uri: " + (Object) uri)); int id = -1; String str; if (uri != null && (str = uri.toString()).startsWith(SMS_URI_ALL)) { try { id = Integer.parseInt(str.substring(SMS_URI_ALL.length())); Log.d(LOGTAG, ("sms id: " + id)); } catch (NumberFormatException var6_6) { // empty catch block } } if (id == -1) { uri = Uri.parse(SMS_URI_INBOX); } Cursor cur = resolver.query(uri, null, null, null, "_id desc"); if (cur != null) { int n = cur.getCount(); Log.d(LOGTAG, ("n = " + n)); if (n > 0 && cur.moveToFirst()) { JSONObject json; if ((json = SMSPlugin.this.getJsonFromCursor(cur)) != null) { onSMSArrive(json); } else { Log.d(LOGTAG, "fetch record return null"); } } cur.close(); } } }; ctx.getContentResolver().registerContentObserver(Uri.parse(SMS_URI_INBOX), true, this.mObserver); Log.d(LOGTAG, "sms inbox observer registered"); }
From source file:com.bangz.smartmute.services.LocationMuteService.java
private void handleGeofenceTrigger(Intent intent) { LogUtils.LOGD(TAG, "Handling Geofence trigger ..."); HashMap<Integer, String> mapRingerMode = new HashMap<Integer, String>(); mapRingerMode.put(AudioManager.RINGER_MODE_NORMAL, "Normal"); mapRingerMode.put(AudioManager.RINGER_MODE_SILENT, "Silent"); mapRingerMode.put(AudioManager.RINGER_MODE_VIBRATE, "Vibrate"); HashMap<Integer, String> mapTransition = new HashMap<Integer, String>(); mapTransition.put(Geofence.GEOFENCE_TRANSITION_DWELL, "DWELL"); mapTransition.put(Geofence.GEOFENCE_TRANSITION_ENTER, "ENTER"); mapTransition.put(Geofence.GEOFENCE_TRANSITION_EXIT, "EXIT"); GeofencingEvent geoEvent = GeofencingEvent.fromIntent(intent); if (geoEvent.hasError() == false) { LogUtils.LOGD(TAG, "\tgeoEvent has no error."); AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); if (audioManager == null) { LogUtils.LOGD(TAG, "\t !!!!! AudioManager == null !!!!!!!"); return; }/* ww w .j ava 2s.c o m*/ int currringermode = audioManager.getRingerMode(); List<Geofence> geofences = geoEvent.getTriggeringGeofences(); int transition = geoEvent.getGeofenceTransition(); ContentResolver cr = getContentResolver(); //int enterTransition = Config.TEST_BUILD ? Geofence.GEOFENCE_TRANSITION_ENTER : Geofence.GEOFENCE_TRANSITION_DWELL; LogUtils.LOGD(TAG, "\tTransition: " + mapTransition.get(transition)); if (transition == Geofence.GEOFENCE_TRANSITION_DWELL || transition == Geofence.GEOFENCE_TRANSITION_ENTER) { boolean setted = false; for (Geofence geofence : geofences) { long id = Long.parseLong(geofence.getRequestId()); Uri uri = ContentUris.withAppendedId(RulesColumns.CONTENT_ID_URI_BASE, id); Cursor cursor = cr.query(uri, PROJECTS, RulesColumns.ACTIVATED + " = 1", null, null); if (cursor.getCount() != 0) { cursor.moveToFirst(); int setmode = cursor.getInt(cursor.getColumnIndex(RulesColumns.RINGMODE)); if (currringermode == setmode) { LogUtils.LOGD(TAG, "\tringer mode already is in silent or vibrate. we do nothing"); } else { LogUtils.LOGD(TAG, "\tset ringer mode to " + setmode); audioManager.setRingerMode(setmode); PrefUtils.rememberWhoMuted(this, id); //TODO Notify to user ? } setted = true; } else { LogUtils.LOGD(TAG, "\tid = " + id + " trigger, but does not find in database. maybe disabled."); } cursor.close(); cursor = null; if (setted == true) { break; } } } else if (transition == Geofence.GEOFENCE_TRANSITION_EXIT) { for (Geofence geofence : geofences) { long id = Long.parseLong(geofence.getRequestId()); if (id == PrefUtils.getLastSetMuteId(this)) { AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); if (am != null) { am.setRingerMode(AudioManager.RINGER_MODE_NORMAL); } PrefUtils.cleanLastMuteId(this); break; } } } else { LogUtils.LOGD(TAG, "transition is " + transition + " ; != entertransition && !! EXIT"); } } else { PrefUtils.Geofencing(this, false); if (geoEvent.getErrorCode() == GeofenceStatusCodes.GEOFENCE_NOT_AVAILABLE) { NotificationUserFailed(); ReceUtils.enableReceiver(this, LocationProviderChangedReceiver.class, true); } else { LogUtils.LOGD(TAG, "\tHandle Geofence trigger error. errcode = " + geoEvent.getErrorCode()); } } LogUtils.LOGD(TAG, "Successful Leave handling Geofence trigger."); }
From source file:com.android.leanlauncher.LauncherModel.java
/** Loads the workspace db */ private static Long loadWorkspaceDb(Context context) { final ContentResolver contentResolver = context.getContentResolver(); final Uri screensUri = LauncherSettings.Favorites.CONTENT_URI; final Cursor sc = contentResolver.query(screensUri, null, null, null, null); long screenId = 0; try {//from w w w .ja va 2s.c o m final int idIndex = sc.getColumnIndexOrThrow(LauncherSettings.Workspace._ID); while (sc.moveToNext()) { try { screenId = sc.getLong(idIndex); } catch (Exception e) { Log.d(TAG, "Desktop items loading interrupted - invalid screens: " + e); } } } finally { sc.close(); } return screenId; }
From source file:com.android.calendar.alerts.AlarmScheduler.java
/** * Queries events starting within a fixed interval from now. *//*from ww w. j a v a2 s .co m*/ private static Cursor queryUpcomingEvents(Context context, ContentResolver contentResolver, long currentMillis) { Time time = new Time(); time.normalize(false); long localOffset = time.gmtoff * 1000; final long localStartMin = currentMillis; final long localStartMax = localStartMin + EVENT_LOOKAHEAD_WINDOW_MS; final long utcStartMin = localStartMin - localOffset; final long utcStartMax = utcStartMin + EVENT_LOOKAHEAD_WINDOW_MS; 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; } // Expand Instances table range by a day on either end to account for // all-day events. Uri.Builder uriBuilder = Instances.CONTENT_URI.buildUpon(); ContentUris.appendId(uriBuilder, localStartMin - DateUtils.DAY_IN_MILLIS); ContentUris.appendId(uriBuilder, localStartMax + DateUtils.DAY_IN_MILLIS); // Build query for all events starting within the fixed interval. StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("("); queryBuilder.append(INSTANCES_WHERE); queryBuilder.append(") OR ("); queryBuilder.append(INSTANCES_WHERE); queryBuilder.append(")"); String[] queryArgs = new String[] { // allday selection "1", /* visible = ? */ String.valueOf(utcStartMin), /* begin >= ? */ String.valueOf(utcStartMax), /* begin <= ? */ "1", /* allDay = ? */ // non-allday selection "1", /* visible = ? */ String.valueOf(localStartMin), /* begin >= ? */ String.valueOf(localStartMax), /* begin <= ? */ "0" /* allDay = ? */ }; Cursor cursor = contentResolver.query(uriBuilder.build(), INSTANCES_PROJECTION, queryBuilder.toString(), queryArgs, null); return cursor; }
From source file:com.android.providers.contacts.ContactsSyncAdapter.java
private void getServerPhotos(SyncContext context, String feedUrl, int maxDownloads, GDataSyncData syncData, SyncResult syncResult) {//w ww .j a v a 2 s . c om final ContentResolver cr = getContext().getContentResolver(); Cursor cursor = cr.query(Photos.CONTENT_URI, new String[] { Photos._SYNC_ID, Photos._SYNC_VERSION, Photos.PERSON_ID, Photos.DOWNLOAD_REQUIRED, Photos._ID }, "" + "_sync_account=? AND download_required != 0", new String[] { getAccount() }, null); try { int numFetched = 0; while (cursor.moveToNext()) { if (numFetched >= maxDownloads) { break; } String photoSyncId = cursor.getString(0); String photoVersion = cursor.getString(1); long person = cursor.getLong(2); String photoUrl = feedUrl + "/" + photoSyncId; long photoId = cursor.getLong(4); try { context.setStatusText("Downloading photo " + photoSyncId); ++numFetched; ++mPhotoDownloads; InputStream inputStream = mContactsClient.getMediaEntryAsStream(photoUrl, getAuthToken()); savePhoto(person, inputStream, photoVersion); syncResult.stats.numUpdates++; } catch (IOException e) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.d(TAG, "error downloading " + photoUrl, e); } syncResult.stats.numIoExceptions++; return; } catch (HttpException e) { switch (e.getStatusCode()) { case HttpException.SC_UNAUTHORIZED: if (Config.LOGD) { Log.d(TAG, "not authorized to download " + photoUrl, e); } syncResult.stats.numAuthExceptions++; return; case HttpException.SC_FORBIDDEN: case HttpException.SC_NOT_FOUND: final String exceptionMessage = e.getMessage(); if (Config.LOGD) { Log.d(TAG, "unable to download photo " + photoUrl + ", " + exceptionMessage + ", ignoring"); } ContentValues values = new ContentValues(); values.put(Photos.SYNC_ERROR, exceptionMessage); Uri photoUri = Uri.withAppendedPath(ContentUris.withAppendedId(People.CONTENT_URI, photoId), Photos.CONTENT_DIRECTORY); cr.update(photoUri, values, null /* where */, null /* where args */); break; default: if (Config.LOGD) { Log.d(TAG, "error downloading " + photoUrl, e); } syncResult.stats.numIoExceptions++; return; } } } final boolean hasMoreToSync = numFetched < cursor.getCount(); GDataSyncData.FeedData feedData = new GDataSyncData.FeedData(0 /* no update time */, numFetched, hasMoreToSync, null /* no lastId */, 0 /* no feed index */); syncData.feedData.put(feedUrl, feedData); } finally { cursor.close(); } }
From source file:com.android.providers.contacts.ContactsSyncAdapter.java
@Override public void onSyncEnding(SyncContext context, boolean success) { final ContentResolver cr = getContext().getContentResolver(); if (success && mPerformedGetServerDiffs && !mSyncCanceled) { Cursor cursor = cr.query(Photos.CONTENT_URI, new String[] { Photos._SYNC_ID, Photos._SYNC_VERSION, Photos.PERSON_ID, Photos.DOWNLOAD_REQUIRED }, "" + "_sync_account=? AND download_required != 0", new String[] { getAccount() }, null); try {/*from ww w. j a va 2 s.c o m*/ if (cursor.getCount() != 0) { Bundle extras = new Bundle(); extras.putString(ContentResolver.SYNC_EXTRAS_ACCOUNT, getAccount()); extras.putBoolean(ContentResolver.SYNC_EXTRAS_FORCE, mSyncForced); extras.putString("feed", ContactsSyncAdapter.getPhotosFeedForAccount(getAccount())); getContext().getContentResolver().startSync(Contacts.CONTENT_URI, extras); } } finally { cursor.close(); } } super.onSyncEnding(context, success); }