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:org.planetmono.dcuploader.ActivityUploader.java
private int queryOrientation(Uri uri) { Log.d(Application.TAG, "querying " + uri.toString()); ContentResolver cr = ActivityUploader.this.getContentResolver(); int orientation = 0; Cursor c = cr.query(uri, new String[] { MediaStore.Images.ImageColumns.ORIENTATION, }, null, null, null); if (c != null) { c.moveToFirst();/*ww w. j av a2 s. co m*/ orientation = c.getInt(0); c.close(); return orientation; } /* If there's no such item in ContentResolver, query EXIF */ return queryExifOrientation(uri.getPath()); }
From source file:com.robotoworks.mechanoid.db.SQuery.java
public int count(Uri uri) { ContentResolver resolver = Mechanoid.getContentResolver(); Cursor c = null;//from w w w. jav a 2 s .c o m uri = uri.buildUpon().appendQueryParameter(MechanoidContentProvider.PARAM_NOTIFY, "false").build(); try { c = resolver.query(uri, new String[] { "count(*)" }, toString(), getArgsArray(), null); int count = 0; if (c.moveToFirst()) { count = c.getInt(0); } return count; } finally { Closeables.closeSilently(c); } }
From source file:com.flipzu.flipzu.Player.java
private boolean isScreenReaderActive() { // Restrict the set of intents to only accessibility services that have // the category FEEDBACK_SPOKEN (aka, screen readers). Intent screenReaderIntent = new Intent(SCREENREADER_INTENT_ACTION); screenReaderIntent.addCategory(SCREENREADER_INTENT_CATEGORY); List<ResolveInfo> screenReaders = getPackageManager().queryIntentServices(screenReaderIntent, 0); ContentResolver cr = getContentResolver(); Cursor cursor = null;/*from www . ja v a 2 s. co m*/ int status = 0; for (ResolveInfo screenReader : screenReaders) { // All screen readers are expected to implement a content provider // that responds to // content://<nameofpackage>.providers.StatusProvider cursor = cr.query( Uri.parse("content://" + screenReader.serviceInfo.packageName + ".providers.StatusProvider"), null, null, null, null); if (cursor != null) { cursor.moveToFirst(); // These content providers use a special cursor that only has // one element, // an integer that is 1 if the screen reader is running. status = cursor.getInt(0); cursor.close(); if (status == 1) { return true; } } } return false; }
From source file:com.example.android.network.sync.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.// w ww . ja v a 2 s . c o m * * <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 ContentResolver contentResolver = getContext().getContentResolver(); Log.i(TAG, "Parsing stream as Atom feed"); final List<Transformer> entries = null; /*=this.parseTransformersResponse(stream)*/; ; Log.i(TAG, "Parsing complete. Found " + entries.size() + " entries"); ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); // Build hash table of incoming entries HashMap<String, Transformer> entryMap = new HashMap<String, Transformer>(); for (Transformer e : entries) { entryMap.put(e.transformerID, e); } Cursor c = null; try { // Get list of all items Log.i(TAG, "Fetching local entries for merge"); Uri uri = Transformer.CONTENT_URI; // Get all entries c = contentResolver.query(uri, null, null, null, null); assert c != null; Log.i(TAG, "Found " + c.getCount() + " local entries. Computing merge solution..."); } catch (Exception ex) { } // Find stale data String id; String name; String location; while (c.moveToNext()) { syncResult.stats.numEntries++; id = c.getColumnName(COLUMN_ID); name = c.getString(COLUMN_ENTRY_ID); location = c.getString(COLUMN_TITLE); Transformer match = entryMap.get(id); if (match != null) { // Entry exists. Remove from entry map to prevent insert later. entryMap.remove(id); // Check to see if the entry needs to be updated Uri existingUri = Transformer.CONTENT_URI.buildUpon().appendPath(id).build(); if ((match.trsName != null && !match.trsLocation.equals(name))) { // Update existing record Log.i(TAG, "Scheduling update: " + existingUri); batch.add(ContentProviderOperation.newUpdate(existingUri).withValue(Transformer.KEY_NAME, name) .withValue(Transformer.KEY_LOCATION, location) .build()); syncResult.stats.numUpdates++; } else { Log.i(TAG, "No action: " + existingUri); } } else { // Entry doesn't exist. Remove it from the database. Uri deleteUri = Transformer.CONTENT_URI.buildUpon().appendPath(id).build(); Log.i(TAG, "Scheduling delete: " + deleteUri); batch.add(ContentProviderOperation.newDelete(deleteUri).build()); syncResult.stats.numDeletes++; } } c.close(); // Add new items for (Transformer e : entryMap.values()) { Log.i(TAG, "Scheduling insert: entry_id=" + e.transformerID); batch.add(ContentProviderOperation.newInsert(Transformer.CONTENT_URI) .withValue(Transformer.KEY_TRANSFORMER_ID, e.transformerID) .withValue(Transformer.KEY_NAME, e.trsName).withValue(Transformer.KEY_LOCATION, e.trsLocation) .withValue(Transformer.KEY_CURRENT_TEMP, e.trsCurrentTemp) .withValue(Transformer.KEY_LAST_SERVER_SYNC_DATE, e.lastServerSyncDate) .withValue(Transformer.KEY_LAST_UPDATED_TIME, e.lastServerSyncDate) .withValue(Transformer.KEY_SYNC_STATUS, 0).withValue(Transformer.KEY_MAKE, e.trsMake) .withValue(Transformer.KEY_WINDING_MAKE, e.trsWindingMake) .withValue(Transformer.KEY_WINDING_COUNT, e.trsWindingCount) .withValue(Transformer.KEY_OIL_LEVEL, e.trsOilLevel) .withValue(Transformer.KEY_OPERATING_POWER, e.trsOperatingPower) .withValue(Transformer.KEY_TYPE, e.trsType) .build()); syncResult.stats.numInserts++; } Log.i(TAG, "Merge solution ready. Applying batch update"); mContentResolver.applyBatch(Transformer.CONTENT_AUTHORITY, batch); mContentResolver.notifyChange(Transformer.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:com.robotoworks.mechanoid.db.SQuery.java
public Cursor select(Uri uri, String[] projection, String sortOrder, boolean enableNotifications) { ContentResolver resolver = Mechanoid.getContentResolver(); uri = uri.buildUpon()/*from ww w .j ava 2s.c o m*/ .appendQueryParameter(MechanoidContentProvider.PARAM_NOTIFY, String.valueOf(enableNotifications)) .build(); return resolver.query(uri, projection, toString(), getArgsArray(), sortOrder); }
From source file:com.android.exchange.adapter.EmailSyncAdapter.java
/** * Serialize commands to delete items from the server; as we find items to delete, add their * id's to the deletedId's array *//from www . jav a 2 s . co m * @param s the Serializer we're using to create post data * @param deletedIds ids whose deletions are being sent to the server * @param first whether or not this is the first command being sent * @return true if SYNC_COMMANDS hasn't been sent (false otherwise) * @throws IOException */ @VisibleForTesting boolean sendDeletedItems(Serializer s, ArrayList<Long> deletedIds, boolean first) throws IOException { ContentResolver cr = mContext.getContentResolver(); // Find any of our deleted items Cursor c = cr.query(Message.DELETED_CONTENT_URI, Message.LIST_PROJECTION, MessageColumns.MAILBOX_KEY + '=' + mMailbox.mId, null, null); // We keep track of the list of deleted item id's so that we can remove them from the // deleted table after the server receives our command deletedIds.clear(); try { while (c.moveToNext()) { String serverId = c.getString(Message.LIST_SERVER_ID_COLUMN); // Keep going if there's no serverId if (serverId == null) { continue; // Also check if this message is referenced elsewhere } else if (messageReferenced(cr, c.getLong(Message.CONTENT_ID_COLUMN))) { userLog("Postponing deletion of referenced message: ", serverId); continue; } else if (first) { s.start(Tags.SYNC_COMMANDS); first = false; } // Send the command to delete this message s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end(); deletedIds.add(c.getLong(Message.LIST_ID_COLUMN)); } } finally { c.close(); } return first; }
From source file:com.vignesh.conf.MainActivity.java
@Override protected void onResume() { super.onResume(); List<String> list = new ArrayList<>(); final ListView listView = (ListView) findViewById(R.id.info); Cursor cursor;//from www. j av a 2 s. c om long time = new Date().getTime(); ContentResolver contentResolver = getContentResolver(); Uri uri = CalendarContract.Calendars.CONTENT_URI; SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(getApplicationContext()); String cal = sharedPreferences.getString(CALENDAR_NAME, getResources().getString(R.string.no_calendar)); String selection = "((" + CalendarContract.Calendars.ACCOUNT_NAME + " = ?))"; int hours_before = Integer.valueOf(sharedPreferences.getString("past_hours", "2")); int hours_future = Integer.valueOf(sharedPreferences.getString("future_hours", "24")); String[] selectionArgs = new String[] { cal }; if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) { Toast.makeText(getApplicationContext(), "No calendar permission", Toast.LENGTH_LONG).show(); finish(); return; } if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { Toast.makeText(getApplicationContext(), "No calling permission", Toast.LENGTH_LONG).show(); finish(); return; } cursor = contentResolver.query(uri, CAL_PROJECTION, selection, selectionArgs, null); assert cursor != null; while (cursor.moveToNext()) { long calID = 0; // Get the field values calID = cursor.getLong(PROJECTION_ID_INDEX); Uri.Builder instanceUriBuilder = CalendarContract.Instances.CONTENT_URI.buildUpon(); ContentUris.appendId(instanceUriBuilder, time - hours_before * 60 * 60 * 1000); ContentUris.appendId(instanceUriBuilder, time + hours_future * 60 * 60 * 1000); Uri instanceUri = instanceUriBuilder.build(); String instanceSelection = "((" + CalendarContract.Instances.CALENDAR_ID + "= ?))"; String[] instanceSelectionArgs = new String[] { "" + calID }; Cursor instanceCursor = contentResolver.query(instanceUri, INSTANCE_PROJECTION, instanceSelection, instanceSelectionArgs, CalendarContract.Instances.BEGIN + " ASC"); assert instanceCursor != null; while (instanceCursor.moveToNext()) { String title = instanceCursor.getString(1); Date begin = new Date(instanceCursor.getLong(2)); Date end = new Date(instanceCursor.getLong(3)); String loc = instanceCursor.getString(4); String desc = instanceCursor.getString(5); String full = title + "\n" + loc + "\n" + desc; Pattern passcodePattern = Pattern .compile(sharedPreferences.getString(REGEX, "(\\d{8})[\\s\\t\\n#]")); Matcher passcodeMatcher = passcodePattern.matcher(full); String list_item = (title + "\n" + "START: " + begin + "\nEND: " + end + "\n"); if (passcodeMatcher.find()) list.add(list_item + "Conf code: " + passcodeMatcher.group().trim() + "\n"); } instanceCursor.close(); } cursor.close(); ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getApplicationContext(), R.layout.list_layout, list); assert listView != null; listView.setAdapter(arrayAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String s = (String) parent.getItemAtPosition(position); SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(getApplicationContext()); String tel = sharedPreferences.getString(CONTACT_NUM, getResources().getString(R.string.no_contact)); Pattern pattern = Pattern.compile(sharedPreferences.getString(REGEX, "(\\d{8})[\\s\\t\\n#]")); Matcher matcher = pattern.matcher(s); if (matcher.find()) { if (!tel.equals(getResources().getString(R.string.no_contact))) { String[] contact = tel.split(": "); String suffix = sharedPreferences.getString(SUFFIX, ""); if (suffix != null) try { suffix = URLEncoder.encode(suffix, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String prefix = sharedPreferences.getString(PREFIX, ""); if (prefix != null) try { prefix = URLEncoder.encode(prefix, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + contact[1] + "%3B" + prefix + matcher.group() + suffix)); if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) { startActivity(intent); } } else { new AlertDialog.Builder(MainActivity.this).setTitle("No contact Selected!") .setMessage("Please Select Conference Call number via Settings Menu").show(); } } } }); }
From source file:com.android.exchange.ExchangeService.java
/** * Return a list of all Accounts in EmailProvider. Because the result of this call may be used * in account reconciliation, an exception is thrown if the result cannot be guaranteed accurate * @param context the caller's context// w w w. j av a2s . c om * @param accounts a list that Accounts will be added into * @return the list of Accounts * @throws ProviderUnavailableException if the list of Accounts cannot be guaranteed valid */ private static AccountList collectEasAccounts(Context context, AccountList accounts) { ContentResolver resolver = context.getContentResolver(); Cursor c = resolver.query(Account.CONTENT_URI, Account.CONTENT_PROJECTION, null, null, null); // We must throw here; callers might use the information we provide for reconciliation, etc. if (c == null) throw new ProviderUnavailableException(); try { ContentValues cv = new ContentValues(); while (c.moveToNext()) { long hostAuthId = c.getLong(Account.CONTENT_HOST_AUTH_KEY_RECV_COLUMN); if (hostAuthId > 0) { HostAuth ha = HostAuth.restoreHostAuthWithId(context, hostAuthId); if (ha != null && ha.mProtocol.equals("eas")) { Account account = new Account(); account.restore(c); // Cache the HostAuth account.mHostAuthRecv = ha; accounts.add(account); // Fixup flags for inbox (should accept moved mail) Mailbox inbox = Mailbox.restoreMailboxOfType(context, account.mId, Mailbox.TYPE_INBOX); if (inbox != null && ((inbox.mFlags & Mailbox.FLAG_ACCEPTS_MOVED_MAIL) == 0)) { cv.put(MailboxColumns.FLAGS, inbox.mFlags | Mailbox.FLAG_ACCEPTS_MOVED_MAIL); resolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, inbox.mId), cv, null, null); } } } } } finally { c.close(); } return accounts; }
From source file:com.google.samples.apps.iosched.service.SessionCalendarService.java
/** * Adds or removes a single session to/from the specified Google Calendar. *//* w ww .j ava 2 s . c om*/ private ArrayList<ContentProviderOperation> processSessionCalendar(final ContentResolver resolver, final long calendarId, final boolean isAddEvent, final Uri sessionUri, final long sessionBlockStart, final long sessionBlockEnd, final String sessionTitle, final String sessionRoom) { ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); // Unable to find the Calendar associated with the user or permissions were revoked. if (calendarId == INVALID_CALENDAR_ID || !permissionsAlreadyGranted()) { return batch; } final String calendarEventTitle = makeCalendarEventTitle(sessionTitle); Cursor cursor; ContentValues values = new ContentValues(); // Add Calendar event. if (isAddEvent) { if (sessionBlockStart == 0L || sessionBlockEnd == 0L || sessionTitle == null) { LOGW(TAG, "Unable to add a Calendar event due to insufficient input parameters."); return batch; } // Check if the calendar event exists first. If it does, we don't want to add a // duplicate one. //noinspection MissingPermission cursor = resolver.query(CalendarContract.Events.CONTENT_URI, // URI new String[] { CalendarContract.Events._ID }, // Projection CalendarContract.Events.CALENDAR_ID + "=? and " // Selection + CalendarContract.Events.TITLE + "=? and " + CalendarContract.Events.DTSTART + ">=? and " + CalendarContract.Events.DTEND + "<=?", new String[] { // Selection args Long.valueOf(calendarId).toString(), calendarEventTitle, Long.toString(Config.CONFERENCE_START_MILLIS), Long.toString(Config.CONFERENCE_END_MILLIS) }, null); long newEventId = -1; if (cursor != null && cursor.moveToFirst()) { // Calendar event already exists for this session. newEventId = cursor.getLong(0); cursor.close(); // Data fix (workaround): batch.add(ContentProviderOperation.newUpdate(CalendarContract.Events.CONTENT_URI) .withValue(CalendarContract.Events.EVENT_TIMEZONE, Config.CONFERENCE_TIMEZONE.getID()) .withSelection(CalendarContract.Events._ID + "=?", new String[] { Long.valueOf(newEventId).toString() }) .build()); // End data fix. } else { // Calendar event doesn't exist, create it. // NOTE: we can't use batch processing here because we need the result of // the insert. values.clear(); values.put(CalendarContract.Events.DTSTART, sessionBlockStart); values.put(CalendarContract.Events.DTEND, sessionBlockEnd); values.put(CalendarContract.Events.EVENT_LOCATION, sessionRoom); values.put(CalendarContract.Events.TITLE, calendarEventTitle); values.put(CalendarContract.Events.CALENDAR_ID, calendarId); values.put(CalendarContract.Events.EVENT_TIMEZONE, Config.CONFERENCE_TIMEZONE.getID()); @SuppressWarnings("MissingPermission") Uri eventUri = resolver.insert(CalendarContract.Events.CONTENT_URI, values); String eventId = eventUri.getLastPathSegment(); if (eventId == null) { return batch; // Should be empty at this point } newEventId = Long.valueOf(eventId); // Since we're adding session reminder to system notification, we're not creating // Calendar event reminders. If we were to create Calendar event reminders, this // is how we would do it. //values.put(CalendarContract.Reminders.EVENT_ID, Integer.valueOf(eventId)); //values.put(CalendarContract.Reminders.MINUTES, 10); //values.put(CalendarContract.Reminders.METHOD, // CalendarContract.Reminders.METHOD_ALERT); // Or default? //cr.insert(CalendarContract.Reminders.CONTENT_URI, values); //values.clear(); } // Update the session in our own provider with the newly created calendar event ID. values.clear(); values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, newEventId); resolver.update(sessionUri, values, null, null); } else { // Remove Calendar event, if exists. // Get the event calendar id. cursor = resolver.query(sessionUri, new String[] { ScheduleContract.Sessions.SESSION_CAL_EVENT_ID }, null, null, null); long calendarEventId = -1; if (cursor != null && cursor.moveToFirst()) { calendarEventId = cursor.getLong(0); cursor.close(); } // Try to remove the Calendar Event based on key. If successful, move on; // otherwise, remove the event based on Event title. int affectedRows = 0; if (calendarEventId != -1) { //noinspection MissingPermission affectedRows = resolver.delete(CalendarContract.Events.CONTENT_URI, CalendarContract.Events._ID + "=?", new String[] { Long.valueOf(calendarEventId).toString() }); } if (affectedRows == 0) { //noinspection MissingPermission resolver.delete(CalendarContract.Events.CONTENT_URI, String.format("%s=? and %s=? and %s=? and %s=?", CalendarContract.Events.CALENDAR_ID, CalendarContract.Events.TITLE, CalendarContract.Events.DTSTART, CalendarContract.Events.DTEND), new String[] { Long.valueOf(calendarId).toString(), calendarEventTitle, Long.valueOf(sessionBlockStart).toString(), Long.valueOf(sessionBlockEnd).toString() }); } // Remove the session and calendar event association. values.clear(); values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, (Long) null); resolver.update(sessionUri, values, null, null); } return batch; }
From source file:com.tct.email.NotificationController.java
/** * query the inbox's folder./* w w w . j a v a 2 s .c o m*/ * @param conentResolver * @param accountId * @return Folder */ private Folder queryUIInboxFolder(ContentResolver conentResolver, long accountId) { Mailbox inbox = Mailbox.restoreMailboxOfType(mContext, accountId, Mailbox.TYPE_INBOX); if (inbox == null) { LogUtils.e(LOG_TAG, "null inbox in queryUIFolder,may account deleted,return"); return null; } Uri folderUri = EmailProvider.uiUri("uifolder", inbox.mId); Cursor folderCursor = conentResolver.query(folderUri, UIProvider.FOLDERS_PROJECTION, null, null, null); Folder folder = null; if (folderCursor != null) { try { if (folderCursor.moveToFirst()) { folder = new Folder(folderCursor); } else { LogUtils.e(LOG_TAG, "Empty folder cursor for account ", "mail uri is", folderUri); return folder; } } finally { folderCursor.close(); } } return folder; }