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.bluetooth.map.BluetoothMapContent.java
static public String getAddressMms(ContentResolver r, long id, int type) { String selection = new String("msg_id=" + id + " AND type=" + type); String uriStr = String.format("content://mms/%d/addr", id); Uri uriAddress = Uri.parse(uriStr);// w ww. j ava 2 s . co m String addr = null; Cursor c = r.query(uriAddress, null, selection, null, null); try { if (c != null && c.moveToFirst()) { addr = c.getString(c.getColumnIndex(Mms.Addr.ADDRESS)); } } finally { close(c); } return addr; }
From source file:com.chaqianma.jd.fragment.PersonalAssetsFragment.java
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { switch (requestCode) { case REQUEST_SDK_IMGS: if (data != null && data.getData() != null) { Uri imgUri = data.getData(); ContentResolver resolver = getActivity().getContentResolver(); String[] pojo = { MediaStore.Images.Media.DATA }; Cursor cursor = null; try { cursor = resolver.query(imgUri, pojo, null, null, null); if (cursor != null && cursor.getCount() > 0) { int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); new Thread(new BaseFragment.ImgRunable(cursor.getString(colunm_index), fileType, selIdxTag, new UpdateUIHandler())).start(); //mHandler.post(new ImgRunable(cursor.getString(colunm_index))); } else { JDToast.showLongText(getActivity(), ""); }//from w w w . ja v a 2 s . c om } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } } } break; case REQUEST_TAKE_PHOTO: // mHandler.post(mRunnable); new Thread( new BaseFragment.ImgRunable(Constants.TEMPPATH, fileType, selIdxTag, new UpdateUIHandler())) .start(); break; default: break; } } }
From source file:com.android.contacts.ContactSaveService.java
/** * Gets the raw contact ids associated with {@param contactId}. * @param contactId/*from w w w . j ava 2 s . co m*/ * @return Array of raw contact ids. */ private long[] getRawContactIds(long contactId) { final ContentResolver resolver = getContentResolver(); long rawContactIds[]; final StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append(RawContacts.CONTACT_ID).append("=").append(String.valueOf(contactId)); final Cursor c = resolver.query(RawContacts.CONTENT_URI, JoinContactQuery.PROJECTION, queryBuilder.toString(), null, null); if (c == null) { Log.e(TAG, "Unable to open Contacts DB cursor"); return null; } try { rawContactIds = new long[c.getCount()]; for (int i = 0; i < rawContactIds.length; i++) { c.moveToPosition(i); final long rawContactId = c.getLong(JoinContactQuery._ID); rawContactIds[i] = rawContactId; } } finally { c.close(); } return rawContactIds; }
From source file:com.akop.bach.parser.PsnEuParser.java
@SuppressLint("DefaultLocale") @Override//ww w .jav a 2s . c om protected void parseFriends(PsnAccount account) throws ParserException, IOException { synchronized (PsnEuParser.class) { ContentResolver cr = mContext.getContentResolver(); ContentValues cv; List<ContentValues> newCvs = new ArrayList<ContentValues>(100); final long accountId = account.getId(); int rowsInserted = 0; int rowsUpdated = 0; int rowsDeleted = 0; long updated = System.currentTimeMillis(); long started = updated; // Handle pending requests String page = getResponse(URL_FRIENDS); Matcher m; Matcher friendMatcher = PATTERN_FRIENDS_PENDING.matcher(page); while (friendMatcher.find()) { String onlineId = htmlDecode(friendMatcher.group(1)); Cursor c = cr.query(Friends.CONTENT_URI, FRIEND_ID_PROJECTION, Friends.ACCOUNT_ID + "=" + account.getId() + " AND " + Friends.ONLINE_ID + "=?", new String[] { onlineId }, null); long friendId = -1; try { if (c != null && c.moveToFirst()) friendId = c.getLong(0); } finally { if (c != null) c.close(); } cv = new ContentValues(15); cv.put(Friends.DELETE_MARKER, updated); cv.put(Friends.ONLINE_STATUS, PSN.STATUS_PENDING); if (friendId < 0) { // New cv.put(Friends.ONLINE_ID, onlineId); cv.put(Friends.ACCOUNT_ID, accountId); cv.put(Friends.PROGRESS, 0); cv.putNull(Friends.ICON_URL); cv.put(Friends.LEVEL, 0); cv.put(Friends.TROPHIES_PLATINUM, 0); cv.put(Friends.TROPHIES_GOLD, 0); cv.put(Friends.TROPHIES_SILVER, 0); cv.put(Friends.TROPHIES_BRONZE, 0); cv.putNull(Friends.PLAYING); cv.put(Friends.LAST_UPDATED, 0); newCvs.add(cv); } else { cr.update(ContentUris.withAppendedId(Friends.CONTENT_URI, friendId), cv, null, null); rowsUpdated++; } } // Handle rest of friends page = getResponse(URL_FRIENDS_AJAX); friendMatcher = PATTERN_FRIENDS.matcher(page); while (friendMatcher.find()) { String friendData = friendMatcher.group(1); String onlineId; if (!(m = PATTERN_FRIEND_ONLINE_ID.matcher(friendData)).find()) continue; onlineId = htmlDecode(m.group(1)); int level = 0; if ((m = PATTERN_FRIEND_LEVEL.matcher(friendData)).find()) level = Integer.parseInt(m.group(1)); String iconUrl = null; if ((m = PATTERN_FRIEND_AVATAR.matcher(friendData)).find()) iconUrl = getLargeAvatarIcon(resolveImageUrl(URL_FRIENDS_AJAX, m.group(1))); String comment = null; if ((m = PATTERN_FRIEND_COMMENT.matcher(friendData)).find()) { comment = htmlDecode(m.group(1)); if (comment != null && comment.equals("null")) comment = null; } int memberType = PSN.MEMBER_TYPE_FREE; if ((m = PATTERN_FRIEND_IS_PLUS.matcher(friendData)).find() && m.group(1).equalsIgnoreCase("true")) { memberType = PSN.MEMBER_TYPE_PLUS; } int bronze = 0; int silver = 0; int gold = 0; int platinum = 0; m = PATTERN_FRIEND_TROPHY.matcher(friendData); 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)); } boolean inGame = false; int status = PSN.STATUS_OTHER; if ((m = PATTERN_FRIEND_STATUS.matcher(friendData)).find()) { String presence = m.group(1).toLowerCase(); if (presence.equals("offline")) status = PSN.STATUS_OFFLINE; else if (presence.equals("online")) status = PSN.STATUS_ONLINE; else if (presence.equals("online-ingame")) { status = PSN.STATUS_ONLINE; inGame = true; } else if (presence.equals("online-away")) status = PSN.STATUS_AWAY; else if (presence.equals("online-ingame-away")) { status = PSN.STATUS_AWAY; inGame = true; } else if (presence.equals("pending")) status = PSN.STATUS_PENDING; } String playing = null; if ((m = PATTERN_FRIEND_PLAYING.matcher(friendData)).find()) { String activity = htmlDecode(m.group(1)).trim(); if (activity != null && activity.length() > 0) { if (inGame) playing = mContext.getString(R.string.playing_f, activity); else playing = activity; } } Cursor c = cr.query(Friends.CONTENT_URI, FRIEND_ID_PROJECTION, Friends.ACCOUNT_ID + "=" + account.getId() + " AND " + Friends.ONLINE_ID + "=?", new String[] { onlineId }, null); long friendId = -1; try { if (c != null && c.moveToFirst()) friendId = c.getLong(0); } finally { if (c != null) c.close(); } cv = new ContentValues(15); cv.put(Friends.ICON_URL, iconUrl); cv.put(Friends.LEVEL, level); cv.put(Friends.MEMBER_TYPE, memberType); cv.put(Friends.COMMENT, comment); cv.put(Friends.LEVEL, level); cv.put(Friends.ONLINE_STATUS, status); 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.PLAYING, playing); cv.put(Friends.DELETE_MARKER, updated); if (friendId < 0) { // New cv.put(Friends.ONLINE_ID, onlineId); cv.put(Friends.ACCOUNT_ID, accountId); cv.put(Friends.PROGRESS, 0); cv.put(Friends.LAST_UPDATED, 0); newCvs.add(cv); } else { cr.update(ContentUris.withAppendedId(Friends.CONTENT_URI, friendId), cv, null, null); rowsUpdated++; } } // Remove friends rowsDeleted = cr.delete(Friends.CONTENT_URI, Friends.ACCOUNT_ID + "=" + accountId + " AND " + Friends.DELETE_MARKER + "!=" + updated, null); if (newCvs.size() > 0) { ContentValues[] cvs = new ContentValues[newCvs.size()]; newCvs.toArray(cvs); rowsInserted = cr.bulkInsert(Friends.CONTENT_URI, cvs); } account.refresh(Preferences.get(mContext)); account.setLastFriendUpdate(System.currentTimeMillis()); account.save(Preferences.get(mContext)); cr.notifyChange(Friends.CONTENT_URI, null); if (App.getConfig().logToConsole()) started = displayTimeTaken("Friend page processing [I:" + rowsInserted + ";U:" + rowsUpdated + ";D:" + rowsDeleted + "]", started); } }
From source file:com.android.contacts.ContactSaveService.java
private void joinContacts(Intent intent) { long contactId1 = intent.getLongExtra(EXTRA_CONTACT_ID1, -1); long contactId2 = intent.getLongExtra(EXTRA_CONTACT_ID2, -1); // Load raw contact IDs for all raw contacts involved - currently edited and selected // in the join UIs. long rawContactIds[] = getRawContactIdsForAggregation(contactId1, contactId2); if (rawContactIds == null) { Log.e(TAG, "Invalid arguments for joinContacts request"); return;//w ww . j av a 2s .c o m } ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(); // For each pair of raw contacts, insert an aggregation exception for (int i = 0; i < rawContactIds.length; i++) { for (int j = 0; j < rawContactIds.length; j++) { if (i != j) { buildJoinContactDiff(operations, rawContactIds[i], rawContactIds[j]); } } } final ContentResolver resolver = getContentResolver(); // Use the name for contactId1 as the name for the newly aggregated contact. final Uri contactId1Uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId1); final Uri entityUri = Uri.withAppendedPath(contactId1Uri, Contacts.Entity.CONTENT_DIRECTORY); Cursor c = resolver.query(entityUri, ContactEntityQuery.PROJECTION, ContactEntityQuery.SELECTION, null, null); if (c == null) { Log.e(TAG, "Unable to open Contacts DB cursor"); showToast(R.string.contactSavedErrorToast); return; } long dataIdToAddSuperPrimary = -1; try { if (c.moveToFirst()) { dataIdToAddSuperPrimary = c.getLong(ContactEntityQuery.DATA_ID); } } finally { c.close(); } // Mark the name from contactId1 IS_SUPER_PRIMARY to make sure that the contact // display name does not change as a result of the join. if (dataIdToAddSuperPrimary != -1) { Builder builder = ContentProviderOperation .newUpdate(ContentUris.withAppendedId(Data.CONTENT_URI, dataIdToAddSuperPrimary)); builder.withValue(Data.IS_SUPER_PRIMARY, 1); builder.withValue(Data.IS_PRIMARY, 1); operations.add(builder.build()); } // Apply all aggregation exceptions as one batch final boolean success = applyOperations(resolver, operations); final String name = queryNameOfLinkedContacts(new long[] { contactId1, contactId2 }); Intent callbackIntent = intent.getParcelableExtra(EXTRA_CALLBACK_INTENT); if (success && name != null) { if (TextUtils.isEmpty(name)) { showToast(R.string.contactsJoinedMessage); } else { showToast(R.string.contactsJoinedNamedMessage, name); } Uri uri = RawContacts.getContactLookupUri(resolver, ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactIds[0])); callbackIntent.setData(uri); LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(BROADCAST_LINK_COMPLETE)); } deliverCallback(callbackIntent); }
From source file:br.com.viniciuscr.notification2android.mediaPlayer.MediaPlaybackService.java
private boolean makeAutoShuffleList() { ContentResolver res = getContentResolver(); Cursor c = null;/*w w w . j a v a 2 s .c o m*/ try { c = res.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Audio.Media._ID }, MediaStore.Audio.Media.IS_MUSIC + "=1", null, null); if (c == null || c.getCount() == 0) { return false; } int len = c.getCount(); long[] list = new long[len]; for (int i = 0; i < len; i++) { c.moveToNext(); list[i] = c.getLong(0); } mAutoShuffleList = list; return true; } catch (RuntimeException ex) { } finally { if (c != null) { c.close(); } } return false; }
From source file:com.android.calendar.alerts.AlarmScheduler.java
/** * Queries for all the reminders of the events in the instancesCursor, and schedules * the alarm for the next upcoming reminder. *///from w w w. j a va2 s. co m private static void queryNextReminderAndSchedule(Cursor instancesCursor, Context context, ContentResolver contentResolver, AlarmManagerInterface alarmManager, int batchSize, long currentMillis) { if (AlertService.DEBUG) { int eventCount = instancesCursor.getCount(); if (eventCount == 0) { Log.d(TAG, "No events found starting within 1 week."); } else { Log.d(TAG, "Query result count for events starting within 1 week: " + eventCount); } } // Put query results of all events starting within some interval into map of event ID to // local start time. Map<Integer, List<Long>> eventMap = new HashMap<Integer, List<Long>>(); Time timeObj = new Time(); long nextAlarmTime = Long.MAX_VALUE; int nextAlarmEventId = 0; instancesCursor.moveToPosition(-1); while (!instancesCursor.isAfterLast()) { int index = 0; eventMap.clear(); StringBuilder eventIdsForQuery = new StringBuilder(); eventIdsForQuery.append('('); while (index++ < batchSize && instancesCursor.moveToNext()) { int eventId = instancesCursor.getInt(INSTANCES_INDEX_EVENTID); long begin = instancesCursor.getLong(INSTANCES_INDEX_BEGIN); boolean allday = instancesCursor.getInt(INSTANCES_INDEX_ALL_DAY) != 0; long localStartTime; if (allday) { // Adjust allday to local time. localStartTime = Utils.convertAlldayUtcToLocal(timeObj, begin, Time.getCurrentTimezone()); } else { localStartTime = begin; } List<Long> startTimes = eventMap.get(eventId); if (startTimes == null) { startTimes = new ArrayList<Long>(); eventMap.put(eventId, startTimes); eventIdsForQuery.append(eventId); eventIdsForQuery.append(","); } startTimes.add(localStartTime); // Log for debugging. if (Log.isLoggable(TAG, Log.DEBUG)) { timeObj.set(localStartTime); StringBuilder msg = new StringBuilder(); msg.append("Events cursor result -- eventId:").append(eventId); msg.append(", allDay:").append(allday); msg.append(", start:").append(localStartTime); msg.append(" (").append(timeObj.format("%a, %b %d, %Y %I:%M%P")).append(")"); Log.d(TAG, msg.toString()); } } if (eventIdsForQuery.charAt(eventIdsForQuery.length() - 1) == ',') { eventIdsForQuery.deleteCharAt(eventIdsForQuery.length() - 1); } eventIdsForQuery.append(')'); // Query the reminders table for the events found. Cursor cursor = null; try { cursor = contentResolver.query(Reminders.CONTENT_URI, REMINDERS_PROJECTION, REMINDERS_WHERE + eventIdsForQuery, null, null); // Process the reminders query results to find the next reminder time. cursor.moveToPosition(-1); while (cursor.moveToNext()) { int eventId = cursor.getInt(REMINDERS_INDEX_EVENT_ID); int reminderMinutes = cursor.getInt(REMINDERS_INDEX_MINUTES); List<Long> startTimes = eventMap.get(eventId); if (startTimes != null) { for (Long startTime : startTimes) { long alarmTime = startTime - reminderMinutes * DateUtils.MINUTE_IN_MILLIS; if (alarmTime > currentMillis && alarmTime < nextAlarmTime) { nextAlarmTime = alarmTime; nextAlarmEventId = eventId; } if (Log.isLoggable(TAG, Log.DEBUG)) { timeObj.set(alarmTime); StringBuilder msg = new StringBuilder(); msg.append("Reminders cursor result -- eventId:").append(eventId); msg.append(", startTime:").append(startTime); msg.append(", minutes:").append(reminderMinutes); msg.append(", alarmTime:").append(alarmTime); msg.append(" (").append(timeObj.format("%a, %b %d, %Y %I:%M%P")).append(")"); Log.d(TAG, msg.toString()); } } } } } finally { if (cursor != null) { cursor.close(); } } } // Schedule the alarm for the next reminder time. if (nextAlarmTime < Long.MAX_VALUE) { scheduleAlarm(context, nextAlarmEventId, nextAlarmTime, currentMillis, alarmManager); } }
From source file:com.dwdesign.tweetings.util.Utils.java
public static List<TabSpec> getTabs(final Context context) { if (context == null) return Collections.emptyList(); final ArrayList<TabSpec> tabs = new ArrayList<TabSpec>(); final ContentResolver resolver = context.getContentResolver(); final Cursor cur = resolver.query(Tabs.CONTENT_URI, Tabs.COLUMNS, null, null, Tabs.DEFAULT_SORT_ORDER); if (cur != null) { cur.moveToFirst();// w w w. jav a2 s . co m final int idx_name = cur.getColumnIndex(Tabs.NAME), idx_icon = cur.getColumnIndex(Tabs.ICON), idx_type = cur.getColumnIndex(Tabs.TYPE), idx_arguments = cur.getColumnIndex(Tabs.ARGUMENTS), idx_position = cur.getColumnIndex(Tabs.POSITION); while (!cur.isAfterLast()) { final int position = cur.getInt(idx_position) + HomeActivity.TAB_POSITION_MESSAGES + 1; final String icon_type = cur.getString(idx_icon); final String type = cur.getString(idx_type); final String name = cur.getString(idx_name); final Bundle args = parseArguments(cur.getString(idx_arguments)); args.putBoolean(INTENT_KEY_IS_HOME_TAB, true); final Class<? extends Fragment> fragment = CUSTOM_TABS_FRAGMENT_MAP.get(type); if (name != null && fragment != null) { tabs.add(new TabSpec(name, getTabIconObject(icon_type), fragment, args, position)); } cur.moveToNext(); } cur.close(); } return tabs; }
From source file:com.dwdesign.tweetings.util.Utils.java
public static long[] getAllStatusesIds(final Context context, final Uri uri, final boolean filter_enabled) { if (context == null) return new long[0]; final ContentResolver resolver = context.getContentResolver(); final ArrayList<Long> ids_list = new ArrayList<Long>(); final Cursor cur = resolver.query(uri, new String[] { Statuses.STATUS_ID }, filter_enabled ? buildFilterWhereClause(getTableNameForContentUri(uri), null) : null, null, null); if (cur == null) return new long[0]; cur.moveToFirst();//from w w w . ja va2s .c o m while (!cur.isAfterLast()) { ids_list.add(cur.getLong(0)); cur.moveToNext(); } cur.close(); return ArrayUtils.fromList(ids_list); }