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.weimed.app.sync.SyncAdapter.java
/** * Read JSON 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./*from w w w. j a 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 updateLocalJSONData(final InputStream stream, final SyncResult syncResult) throws IOException, JSONException, RemoteException, OperationApplicationException, ParseException { final JSONParser JSONParser = new JSONParser(); final ContentResolver contentResolver = getContext().getContentResolver(); Log.i(TAG, "Parsing stream as JSON Array"); final JSONObject json = JSONParser.parseJSONObject(stream); Log.i(TAG, "Parsing complete. Found " + json.getInt("total_rows") + " entries"); ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); // Build hash table of incoming entries HashMap<String, JSONObject> entryMap = new HashMap<String, JSONObject>(); final JSONArray entries = json.getJSONArray("rows"); for (int i = 0; i < json.getInt("total_rows"); i++) { JSONObject e = entries.getJSONObject(i).getJSONObject("value"); entryMap.put(e.getString("_id"), e); } // Get list of all items Log.i(TAG, "Fetching local entries for merge"); Uri uri = NewsContract.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 content; String publisher; String picurl; String originalurl; String createdat; String updatedat; String publishedat; while (c.moveToNext()) { syncResult.stats.numEntries++; id = c.getInt(COLUMN_ID); entryId = c.getString(COLUMN_ENTRY_ID); title = c.getString(COLUMN_TITLE); content = c.getString(COLUMN_CONTENT); publisher = c.getString(COLUMN_PUBLISHER); picurl = c.getString(COLUMN_PICURL); originalurl = c.getString(COLUMN_ORIGINALURL); createdat = c.getString(COLUMN_CREATEDAT); updatedat = c.getString(COLUMN_UPDATEDAT); publishedat = c.getString(COLUMN_PUBLISHEDAT); JSONObject 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 // How to know update local or remote? updatedAt! which is newer, update another. // Uri existingUri = NewsContract.Entry.CONTENT_URI.buildUpon() // .appendPath(Integer.toString(id)).build(); // if ((match.getString("title") != null && !match.getString("title").equals(title)) || // (match.getString("content") != null && !match.getString("content").equals(content)) || // (match.getString("publisher") != null && !match.getString("publisher").equals(publisher)) || // (match.getString("picurl") != null && !match.getString("picurl").equals(picurl)) || // (match.getString("originalurl") != null && !match.getString("originalurl").equals(originalurl)) || // (match.getString("createdat") != null && !match.getString("createdat").equals(createdat)) || // (match.getString("updatedat") != null && !match.getString("updatedat").equals(updatedat)) || // (match.getString("publishedat") != null && !match.getString("publishedat").equals(publishedat)) // ) { // // Update existing record // Log.i(TAG, "Scheduling update: " + existingUri); // batch.add(ContentProviderOperation.newUpdate(existingUri) // .withValue(NewsContract.Entry.COLUMN_TITLE, title) // .withValue(NewsContract.Entry.COLUMN_CONTENT, content) // .withValue(NewsContract.Entry.COLUMN_PUBLISHER, publisher) // .withValue(NewsContract.Entry.COLUMN_PICURL, picurl) // .withValue(NewsContract.Entry.COLUMN_ORIGINALURL, originalurl) // .withValue(NewsContract.Entry.COLUMN_CREATEDAT, createdat) // .withValue(NewsContract.Entry.COLUMN_UPDATEDAT, updatedat) // .withValue(NewsContract.Entry.COLUMN_PUBLISHEDAT, publishedat) // .build()); // syncResult.stats.numUpdates++; // } else { // Log.i(TAG, "No action: " + existingUri); // } // } else { // Entry doesn't exist. Remove it from the database. Uri deleteUri = NewsContract.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 (JSONObject e : entryMap.values()) { Log.i(TAG, "Scheduling insert: entry_id=" + e.getString("_id")); batch.add(ContentProviderOperation.newInsert(NewsContract.Entry.CONTENT_URI) .withValue(NewsContract.Entry.COLUMN_ENTRY_ID, e.getString("_id")) .withValue(NewsContract.Entry.COLUMN_TITLE, e.getString("title")) .withValue(NewsContract.Entry.COLUMN_CONTENT, fetchTextFileToString(NEWS_URL_BASE + '/' + e.getString("_id") + "/content.md")) .withValue(NewsContract.Entry.COLUMN_PUBLISHER, e.getString("publisher")) .withValue(NewsContract.Entry.COLUMN_PICURL, e.has("pic_link") ? e.getString("pic_link") : null) .withValue(NewsContract.Entry.COLUMN_ORIGINALURL, e.getString("origin_link")) .withValue(NewsContract.Entry.COLUMN_CREATEDAT, e.getString("created_at")) .withValue(NewsContract.Entry.COLUMN_UPDATEDAT, e.getString("updated_at")) .withValue(NewsContract.Entry.COLUMN_PUBLISHEDAT, e.getString("publish_at")).build()); syncResult.stats.numInserts++; } Log.i(TAG, "Merge solution ready. Applying batch update"); mContentResolver.applyBatch(NewsContract.CONTENT_AUTHORITY, batch); mContentResolver.notifyChange(NewsContract.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:com.robotoworks.mechanoid.db.SQuery.java
public Cursor select(Uri uri, String[] projection, String sortOrder) { ContentResolver resolver = Mechanoid.getContentResolver(); return resolver.query(uri, projection, toString(), getArgsArray(), sortOrder); }
From source file:com.phonegap.ContactAccessorSdk3_4.java
@Override /** /*from w w w . j a va2 s.c om*/ * This method takes the fields required and search options in order to produce an * array of contacts that matches the criteria provided. * @param fields an array of items to be used as search criteria * @param options that can be applied to contact searching * @return an array of contacts */ public JSONArray search(JSONArray fields, JSONObject options) { String searchTerm = ""; int limit = Integer.MAX_VALUE; boolean multiple = true; if (options != null) { searchTerm = options.optString("filter"); if (searchTerm.length() == 0) { searchTerm = "%"; } else { searchTerm = "%" + searchTerm + "%"; } try { multiple = options.getBoolean("multiple"); if (!multiple) { limit = 1; } } catch (JSONException e) { // Multiple was not specified so we assume the default is true. } } else { searchTerm = "%"; } ContentResolver cr = mApp.getContentResolver(); Set<String> contactIds = buildSetOfContactIds(fields, searchTerm); HashMap<String, Boolean> populate = buildPopulationSet(fields); Iterator<String> it = contactIds.iterator(); JSONArray contacts = new JSONArray(); JSONObject contact; String contactId; int pos = 0; while (it.hasNext() && (pos < limit)) { contact = new JSONObject(); try { contactId = it.next(); contact.put("id", contactId); // Do query for name and note Cursor cur = cr.query(People.CONTENT_URI, new String[] { People.DISPLAY_NAME, People.NOTES }, PEOPLE_ID_EQUALS, new String[] { contactId }, null); cur.moveToFirst(); if (isRequired("displayName", populate)) { contact.put("displayName", cur.getString(cur.getColumnIndex(People.DISPLAY_NAME))); } if (isRequired("phoneNumbers", populate)) { contact.put("phoneNumbers", phoneQuery(cr, contactId)); } if (isRequired("emails", populate)) { contact.put("emails", emailQuery(cr, contactId)); } if (isRequired("addresses", populate)) { contact.put("addresses", addressQuery(cr, contactId)); } if (isRequired("organizations", populate)) { contact.put("organizations", organizationQuery(cr, contactId)); } if (isRequired("ims", populate)) { contact.put("ims", imQuery(cr, contactId)); } if (isRequired("note", populate)) { contact.put("note", cur.getString(cur.getColumnIndex(People.NOTES))); } // nickname // urls // relationship // birthdays // anniversary pos++; cur.close(); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); } contacts.put(contact); } return contacts; }
From source file:com.nachiket.titan.LibraryActivity.java
/** * Set a new limiter of the given type built from the first * MediaStore.Audio.Media row that matches the selection. * * @param limiterType The type of limiter to create. Must be either * MediaUtils.TYPE_ARTIST or MediaUtils.TYPE_ALBUM. * @param selection Selection to pass to the query. *///from w w w .j a v a 2 s . com private void setLimiter(int limiterType, String selection) { ContentResolver resolver = getContentResolver(); Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; String[] projection = new String[] { MediaStore.Audio.Media.ARTIST_ID, MediaStore.Audio.Media.ALBUM_ID, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM }; Cursor cursor = resolver.query(uri, projection, selection, null, null); if (cursor != null) { if (cursor.moveToNext()) { String[] fields; String data; switch (limiterType) { case MediaUtils.TYPE_ARTIST: fields = new String[] { cursor.getString(2) }; data = String.format("artist_id=%d", cursor.getLong(0)); break; case MediaUtils.TYPE_ALBUM: fields = new String[] { cursor.getString(2), cursor.getString(3) }; data = String.format("album_id=%d", cursor.getLong(1)); break; default: throw new IllegalArgumentException("setLimiter() does not support limiter type " + limiterType); } mPagerAdapter.setLimiter(new Limiter(limiterType, fields, data)); } cursor.close(); } }
From source file:com.android.exchange.EasAccountService.java
private int parsePingResult(InputStream is, ContentResolver cr, HashMap<String, Integer> errorMap) throws IOException, StaleFolderListException, IllegalHeartbeatException, CommandStatusException { PingParser pp = new PingParser(is); if (pp.parse()) { // True indicates some mailboxes need syncing... // syncList has the serverId's of the mailboxes... mBindArguments[0] = Long.toString(mAccount.mId); mPingChangeList = pp.getSyncList(); for (String serverId : mPingChangeList) { mBindArguments[1] = serverId; Cursor c = cr.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, WHERE_ACCOUNT_KEY_AND_SERVER_ID, mBindArguments, null); if (c == null) throw new ProviderUnavailableException(); try { if (c.moveToFirst()) { /**//from w w w. j a v a 2 s . c om * Check the boxes reporting changes to see if there really were any... * We do this because bugs in various Exchange servers can put us into a * looping behavior by continually reporting changes in a mailbox, even when * there aren't any. * * This behavior is seemingly random, and therefore we must code defensively * by backing off of push behavior when it is detected. * * One known cause, on certain Exchange 2003 servers, is acknowledged by * Microsoft, and the server hotfix for this case can be found at * http://support.microsoft.com/kb/923282 */ // Check the status of the last sync String status = c.getString(Mailbox.CONTENT_SYNC_STATUS_COLUMN); int type = ExchangeService.getStatusType(status); // This check should always be true... if (type == ExchangeService.SYNC_PING) { int changeCount = ExchangeService.getStatusChangeCount(status); if (changeCount > 0) { errorMap.remove(serverId); } else if (changeCount == 0) { // This means that a ping reported changes in error; we keep a count // of consecutive errors of this kind String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN); Integer failures = errorMap.get(serverId); if (failures == null) { userLog("Last ping reported changes in error for: ", name); errorMap.put(serverId, 1); } else if (failures > MAX_PING_FAILURES) { // We'll back off of push for this box pushFallback(c.getLong(Mailbox.CONTENT_ID_COLUMN)); continue; } else { userLog("Last ping reported changes in error for: ", name); errorMap.put(serverId, failures + 1); } } } // If there were no problems with previous sync, we'll start another one ExchangeService.startManualSync(c.getLong(Mailbox.CONTENT_ID_COLUMN), ExchangeService.SYNC_PING, null); } } finally { c.close(); } } } return pp.getPingStatus(); }
From source file:com.tct.email.NotificationController.java
/** * Registers an observer for changes to mailboxes in the given account. * NOTE: This must be called on the notification handler thread. * @param accountId The ID of the account to register the observer for. May be * {@link Account#ACCOUNT_ID_COMBINED_VIEW} to register observers for all * accounts that allow for user notification. *//* ww w . j a v a 2 s . com*/ private void registerMessageNotification(final long accountId) { ContentResolver resolver = mContext.getContentResolver(); if (accountId == Account.ACCOUNT_ID_COMBINED_VIEW) { Cursor c = resolver.query(Account.CONTENT_URI, EmailContent.ID_PROJECTION, null, null, null); try { //TS: junwei-xu 2015-12-30 EMAIL BUGFIX-1128322 MOD_S while (c != null && c.moveToNext()) { long id = c.getLong(EmailContent.ID_PROJECTION_COLUMN); registerMessageNotification(id); } //TS: junwei-xu 2015-12-30 EMAIL BUGFIX-1128322 MOD_E } finally { //TS: jian.xu 2015-12-08 EMAIL BUGFIX-1118361 MOD_S if (c != null) { c.close(); } //TS: jian.xu 2015-12-08 EMAIL BUGFIX-1118361 MOD_E } } else { ContentObserver obs = mNotificationMap.get(accountId); if (obs != null) return; // we're already observing; nothing to do LogUtils.i(LOG_TAG, "Registering for notifications for account " + accountId); ContentObserver observer = new MessageContentObserver(sNotificationHandler, mContext, accountId); resolver.registerContentObserver(Message.NOTIFIER_URI, true, observer); mNotificationMap.put(accountId, observer); // Now, ping the observer for any initial notifications observer.onChange(true); } }
From source file:com.akop.bach.parser.PsnEuParser.java
@SuppressLint("DefaultLocale") @Override//w ww . ja v a 2s . c o m protected void parseFriendSummary(PsnAccount account, String friendOnlineId) throws ParserException, IOException { String url = String.format(URL_FRIEND_SUMMARY_f, URLEncoder.encode(friendOnlineId, "UTF-8")); String friendData = getResponse(url); ContentResolver cr = mContext.getContentResolver(); Cursor c = cr.query(Friends.CONTENT_URI, FRIEND_ID_PROJECTION, Friends.ACCOUNT_ID + "=" + account.getId() + " AND " + Friends.ONLINE_ID + "=?", new String[] { friendOnlineId }, null); long updated = System.currentTimeMillis(); long started = updated; long friendId = -1; try { if (c != null && c.moveToFirst()) friendId = c.getLong(0); } finally { if (c != null) c.close(); } Matcher m; Matcher friendMatcher = PATTERN_FRIEND_SUMMARY.matcher(friendData); if (friendMatcher.find() && friendMatcher.find()) // skip the first { String friendCard = friendMatcher.group(1); String onlineId = null; if ((m = PATTERN_FRIEND_SUMMARY_ONLINE_ID.matcher(friendCard)).find()) onlineId = htmlDecode(m.group(1)); if (onlineId != null) { int progress = 0; if ((m = PATTERN_FRIEND_SUMMARY_PROGRESS.matcher(friendCard)).find()) progress = Integer.parseInt(m.group(1)); int level = 0; if ((m = PATTERN_FRIEND_SUMMARY_LEVEL.matcher(friendCard)).find()) level = Integer.parseInt(m.group(1)); String iconUrl = null; if ((m = PATTERN_FRIEND_SUMMARY_AVATAR.matcher(friendCard)).find()) iconUrl = getLargeAvatarIcon(resolveImageUrl(url, m.group(1))); int memberType = PSN.MEMBER_TYPE_FREE; if ((m = PATTERN_FRIEND_SUMMARY_IS_PLUS.matcher(friendCard)).find()) memberType = PSN.MEMBER_TYPE_PLUS; int bronze = 0; int silver = 0; int gold = 0; int platinum = 0; m = PATTERN_FRIEND_SUMMARY_TROPHIES.matcher(friendCard); while (m.find()) { String type = m.group(1).toLowerCase(); if ("bronze".equals(type)) bronze = Integer.parseInt(m.group(2)); else if ("silver".equals(type)) silver = Integer.parseInt(m.group(2)); else if ("gold".equals(type)) gold = Integer.parseInt(m.group(2)); else if ("platinum".equals(type)) platinum = Integer.parseInt(m.group(2)); } ContentValues cv = new ContentValues(15); cv.put(Friends.LAST_UPDATED, updated); cv.put(Friends.ONLINE_ID, onlineId); cv.put(Friends.ICON_URL, iconUrl); cv.put(Friends.LEVEL, level); cv.put(Friends.PROGRESS, progress); cv.put(Friends.TROPHIES_PLATINUM, platinum); cv.put(Friends.TROPHIES_GOLD, gold); cv.put(Friends.TROPHIES_SILVER, silver); cv.put(Friends.TROPHIES_BRONZE, bronze); cv.put(Friends.MEMBER_TYPE, memberType); if (friendId < 0) { // New cv.put(Friends.ACCOUNT_ID, account.getId()); cv.put(Friends.ONLINE_STATUS, PSN.STATUS_OTHER); cv.put(Friends.PLAYING, (String) null); cr.insert(Friends.CONTENT_URI, cv); } else { // Existing cr.update(Friends.CONTENT_URI, cv, Friends._ID + "=" + friendId, null); } cr.notifyChange(Friends.CONTENT_URI, null); } } if (App.getConfig().logToConsole()) started = displayTimeTaken("parseCompareGames/processing", started); }
From source file:org.cryptsecure.Utility.java
/** * Gets the contact id for a Uri contactUri picked by:<BR> * startActivityForResult(new Intent(Intent.ACTION_PICK, * ContactsContract.Contacts.CONTENT_URI), 12345); <BR> * where 12345 is some request code./*from w w w . jav a 2 s. c om*/ * * @param contentResolver * the content resolver * @param contactUri * the contact uri * @return the contact id */ public static String getContactId(ContentResolver contentResolver, Uri contactUri) { String contactId = null; Cursor cursorID = contentResolver.query(contactUri, new String[] { ContactsContract.Contacts._ID }, null, null, null); if (cursorID.moveToFirst()) { contactId = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID)); } cursorID.close(); return contactId; }
From source file:com.hhunj.hhudata.SearchBookContentsActivity.java
public void updatedb(List<SearchBookContentsResult> items) { int max_alarm_time_span = 60; ContentResolver resolver = getApplicationContext().getContentResolver(); ContentValues values = new ContentValues(); for (int i = 0; i < items.size(); i++) { SearchBookContentsResult res = items.get(i); long stationid = Long.parseLong(res.getPageNumber()); values.put(NotePad.Notes.TITLE, res.getName()); values.put(NotePad.Notes.NOTE, ""); values.put(NotePad.Notes.LONGITUTE, 108.0); values.put(NotePad.Notes.LATITUDE, 32.0); values.put(NotePad.Notes.SPEED, 55); values.put(NotePad.Notes.ALTITUDE, 55); values.put(NotePad.Notes.CREATEDDATE, res.getRectime().getTime()); values.put(NotePad.Notes._ID, stationid);//id Uri urlNote = NotePad.Notes.CONTENT_URI; Uri myUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_URI, stationid); Cursor cur = resolver.query(myUri, NotePad.Notes.PROJECTION, null, null, null); if (cur != null && cur.moveToFirst()) { try { long id = cur.getLong(NotePad.Notes._ID_COLUMN); Date oldtime = new Date(cur.getLong(cur.getColumnIndex(NotePad.Notes.CREATEDDATE))); boolean oldalarm = (cur.getInt(NotePad.Notes.ALARM_COLUMN) == 0) ? false : true; long dif = (res.getRectime().getTime() - oldtime.getTime()) / (60 * 1000); dif = ((new Date()).getTime() - oldtime.getTime()) / (60 * 1000); if (dif > max_alarm_time_span) { //... if (oldalarm == false) { Log.w(TAG, "over time err--------"); String phoneNumber = "13338620269"; String message = "over time err--------"; sendSMS(phoneNumber, message); values.put(NotePad.Notes.ALARM, true); }// w ww.j a v a2 s . com } else { values.put(NotePad.Notes.ALARM, false); } } catch (Exception e) { int aa = 0; } int count = resolver.update(myUri, values, null, null); // resolver.update( myUri, values, NotePad.Notes._ID + " = " +res.getPageNumber(), null); if (count == 0) { } } else { try { myUri = resolver.insert(urlNote, values); } catch (IllegalArgumentException e) { throw e; } } } }
From source file:com.tct.email.NotificationController.java
/** * query the account's UIaccount./*from w w w . j a va2s . c o m*/ * @param conentResolver * @param accountId * @return com.tct.mail.providers.Account */ private com.tct.mail.providers.Account queryUIaccount(ContentResolver conentResolver, long accountId) { com.tct.mail.providers.Account account = null; Cursor accountCursor = null; Uri accountUri = EmailProvider.uiUri("uiaccount", accountId); try { accountCursor = conentResolver.query(accountUri, UIProvider.ACCOUNTS_PROJECTION, null, null, null); if (accountCursor == null) { LogUtils.e(LOG_TAG, "Null account cursor for account " + accountUri); return null; } if (accountCursor.moveToFirst()) { account = com.tct.mail.providers.Account.builder().buildFrom(accountCursor); } } catch (Exception e) { LogUtils.e(LOG_TAG, "Exception happen in queryUIaccount." + e); } finally { accountCursor.close(); } if (account == null) { LogUtils.d(LOG_TAG, "Tried to create a notification for a missing account " + accountUri); } return account; }