private String readAddressBookInfo() { StringBuilder res = new StringBuilder(); ContentResolver cr = mActivity.getContentResolver(); StringBuilder sb = new StringBuilder(); if (cr != null) { final int maxRows = 10; sb.append("phone" + "\n\n"); Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); sb.append(getCursorContent(phone, maxRows)); sb.append("email" + "\n\n"); Cursor email = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, null, null, null); sb.append(getCursorContent(email, maxRows)); sb.append("data" + "\n\n"); Cursor data = cr.query(ContactsContract.Data.CONTENT_URI, null, null, null, null); sb.append(getCursorContent(data, maxRows)); } return sb.toString(); }
// Load all available calendars. // If an empty list is returned the caller probably needs to enable calendar // read permissions in App Ops/XPrivacy etc. public static List<AndroidCalendar> loadAll(ContentResolver resolver) { if (missing(resolver, Calendars.CONTENT_URI) || missing(resolver, Events.CONTENT_URI)) return new ArrayList<>(); Cursor cur = resolver.query(Calendars.CONTENT_URI, CAL_COLS, null, null, null); List<AndroidCalendar> calendars = new ArrayList<>(cur.getCount()); while (cur.moveToNext()) { if (getLong(cur, Calendars.DELETED) != 0) continue; AndroidCalendar calendar = new AndroidCalendar(); calendar.mId = getLong(cur, Calendars._ID); calendar.mIdStr = getString(cur, Calendars._ID); calendar.mName = getString(cur, Calendars.NAME); calendar.mDisplayName = getString(cur, Calendars.CALENDAR_DISPLAY_NAME); calendar.mAccountName = getString(cur, Calendars.ACCOUNT_NAME); calendar.mAccountType = getString(cur, Calendars.ACCOUNT_TYPE); calendar.mOwner = getString(cur, Calendars.OWNER_ACCOUNT); calendar.mIsActive = getLong(cur, Calendars.VISIBLE) == 1; calendar.mTimezone = getString(cur, Calendars.CALENDAR_TIME_ZONE); final String[] cols = new String[] {Events._ID}; final String where = Events.CALENDAR_ID + "=?"; final String[] args = new String[] {calendar.mIdStr}; Cursor eventsCur = resolver.query(Events.CONTENT_URI, cols, where, args, null); calendar.mNumEntries = eventsCur.getCount(); eventsCur.close(); calendars.add(calendar); } cur.close(); return calendars; }
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator( tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:26.964 -0500", hash_original_method = "7C7E876780A603240D42A5BB96522037", hash_generated_method = "EAAD1702E472810FAA2CF3F810517246") private static String getTitle(Context context, Uri uri, boolean followSettingsUri) { Cursor cursor = null; ContentResolver res = context.getContentResolver(); String title = null; if (uri != null) { String authority = uri.getAuthority(); if (Settings.AUTHORITY.equals(authority)) { if (followSettingsUri) { Uri actualUri = RingtoneManager.getActualDefaultRingtoneUri( context, RingtoneManager.getDefaultType(uri)); String actualTitle = getTitle(context, actualUri, false); title = context.getString( com.android.internal.R.string.ringtone_default_with_actual, actualTitle); } } else { if (DrmStore.AUTHORITY.equals(authority)) { cursor = res.query(uri, DRM_COLUMNS, null, null, null); } else if (MediaStore.AUTHORITY.equals(authority)) { cursor = res.query(uri, MEDIA_COLUMNS, null, null, null); } try { if (cursor != null && cursor.getCount() == 1) { cursor.moveToFirst(); return cursor.getString(2); } else { title = uri.getLastPathSegment(); } } finally { if (cursor != null) { cursor.close(); } } } } if (title == null) { title = context.getString(com.android.internal.R.string.ringtone_unknown); if (title == null) { title = ""; } } return title; }
@TestTargetNew( level = TestLevel.COMPLETE, method = "getContentUri", args = {String.class}) @ToBeFixed( bug = "1695243", explanation = "Android API javadocs are incomplete. This is no " + "document which describs possible values of the param volumeName.") public void testGetContentUri() { assertNotNull( mContentResolver.query( Artists.getContentUri(MediaStoreAudioTestHelper.INTERNAL_VOLUME_NAME), null, null, null, null)); assertNotNull( mContentResolver.query( Artists.getContentUri(MediaStoreAudioTestHelper.INTERNAL_VOLUME_NAME), null, null, null, null)); // can not accept any other volume names String volume = "fakeVolume"; assertNull(mContentResolver.query(Artists.getContentUri(volume), null, null, null, null)); }
/** * True if the media exists, false otherwise * * @param context * @param id * @param isImage false == video * @return */ public static boolean mediaExists(Context context, int id, boolean isImage) { ContentResolver cr = context.getContentResolver(); Cursor cursor; if (isImage) cursor = cr.query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] {MediaStore.Images.Media.DATA}, ImageColumns._ID + " = ?", new String[] {String.valueOf(id)}, null); else cursor = cr.query( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, new String[] {MediaStore.Video.Media.DATA}, VideoColumns._ID + " = ?", new String[] {String.valueOf(id)}, null); try { if (!cursor.moveToFirst()) return false; if (!new File(cursor.getString(0)).exists()) return false; } finally { cursor.close(); } return true; }
public String queryNumber(String words) { String[] arg = new String[] {"%" + words + "%"}; Cursor contactsCursor = mContentResolver.query( Contacts.CONTENT_URI, DEFAULT_CONTACTS_PROJECTION, CONTACTS_SELECTION_BY_NAME, arg, Contacts.SORT_KEY_PRIMARY); StringBuilder sb = new StringBuilder(); if (contactsCursor == null) { return null; } while (contactsCursor.moveToNext()) { long id = contactsCursor.getLong(CONTACTS_COLUMN_ID); Cursor dataCursor = mContentResolver.query( Data.CONTENT_URI, DEFAULT_DATA_PROJECTION, DATA_SELECTION_BY_CONTACT_ID, new String[] {String.valueOf(id)}, null); if (dataCursor != null) { while (dataCursor.moveToNext()) { log(dataCursor.getString(DATA_COLUMN_NUMBER)); sb.append(dataCursor.getString(DATA_COLUMN_NUMBER)); sb.append(LINE_NUMBER_SPERATOR); } dataCursor.close(); } } contactsCursor.close(); return sb.toString(); }
public static String getMimeTypeForMedia(ContentResolver cr, int id, boolean isImage) { Cursor cursor; if (isImage) cursor = cr.query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] {MediaStore.Images.Media.MIME_TYPE}, ImageColumns._ID + " = ?", new String[] {String.valueOf(id)}, null); else cursor = cr.query( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, new String[] {MediaStore.Video.Media.MIME_TYPE}, VideoColumns._ID + " = ?", new String[] {String.valueOf(id)}, null); try { if (!cursor.moveToFirst()) return null; return cursor.getString(0); } finally { cursor.close(); } }
public void resolve() { ContentResolver resolver = getContentResolver(); Uri uri = Uri.parse("content://com.android.contacts/raw_contacts"); Uri dataUri = Uri.parse("content://com.android.contacts/data"); Cursor cursor = resolver.query(uri, null, null, null, null); while (cursor.moveToNext()) { String id = cursor.getString(cursor.getColumnIndex("contact_id")); Cursor cursor1 = resolver.query(dataUri, null, "raw_contact_id=?", new String[] {id}, null); while (cursor1.moveToNext()) { String data = cursor1.getString(cursor1.getColumnIndex("data1")); String mimetype = cursor1.getString(cursor1.getColumnIndex("mimetype")); String name = cursor1.getString(cursor1.getColumnIndex("display_name")); if (mimetype.equals("vnd.android.cursor.item/phone_v2")) { data = data.replace(" ", ""); phoneNumber.add(data); getImage(data); phoneNumberToId.put(data, id); nameList.add(name); } } cursor1.close(); } cursor.close(); }
// TODO: query with normalized number public String queryName(String number) { if (number == null || number.length() == 0) { return null; } String name = null; Cursor dataCs = mContentResolver.query( Data.CONTENT_URI, DEFAULT_DATA_PROJECTION, DATA_SELECTION_BY_NUMBER, new String[] {number}, null); if (dataCs == null) { return null; } if (dataCs.moveToNext()) { Uri uri = ContentUris.withAppendedId( Contacts.CONTENT_URI, dataCs.getLong(DATA_COLUMN_RAW_CONTACT_ID)); Cursor contactsCs = mContentResolver.query(uri, DEFAULT_CONTACTS_PROJECTION, null, null, null); if (contactsCs == null) { return null; } if (contactsCs.moveToNext()) { name = contactsCs.getString(CONTACTS_COLUMN_DISPLAY_NAME); } contactsCs.close(); } dataCs.close(); return name; }
public static int getChangesCount(ContentResolver resolver) { int changes = 0; Cursor cursor = resolver.query(Edits.CONTENT_URI, Edits.DEFAULT_COLUMNS, null, null, null); if (cursor != null) { changes += cursor.getCount(); cursor.close(); } long file_id = -2; try { file_id = new OrgFile(FileUtils.CAPTURE_FILE, resolver).nodeId; } catch (OrgFileNotFoundException e) { } cursor = resolver.query( OrgData.CONTENT_URI, OrgData.DEFAULT_COLUMNS, OrgData.FILE_ID + "=?", new String[] {Long.toString(file_id)}, null); if (cursor != null) { int captures = cursor.getCount(); if (captures > 0) changes += captures; cursor.close(); } return changes; }
@TestTargetNew( level = TestLevel.COMPLETE, method = "getContentUri", args = {String.class}) @ToBeFixed( bug = "1695243", explanation = "Android API javadocs are incomplete. @throw clause " + "should be added in to javadoc when getting uri for internal volume.") public void testGetContentUri() { assertNotNull( mContentResolver.query( Playlists.getContentUri(MediaStoreAudioTestHelper.EXTERNAL_VOLUME_NAME), null, null, null, null)); // can not accept any other volume names try { assertNotNull( mContentResolver.query( Playlists.getContentUri(MediaStoreAudioTestHelper.INTERNAL_VOLUME_NAME), null, null, null, null)); fail("Should throw SQLException as the internal datatbase has no playlist"); } catch (SQLException e) { // expected } String volume = "fakeVolume"; assertNull(mContentResolver.query(Playlists.getContentUri(volume), null, null, null, null)); }
private void loadAggregationSuggestions(Uri uri) { ContentResolver contentResolver = mContext.getContentResolver(); Cursor cursor = contentResolver.query(uri, new String[] {Contacts._ID}, null, null, null); try { // If a new request is pending, chuck the result of the previous request if (getHandler().hasMessages(MESSAGE_NAME_CHANGE)) { return; } boolean changed = updateSuggestedContactIds(cursor); if (!changed) { return; } StringBuilder sb = new StringBuilder(DataQuery.SELECTION_PREFIX); int count = mSuggestedContactIds.length; for (int i = 0; i < count; i++) { if (i > 0) { sb.append(','); } sb.append(mSuggestedContactIds[i]); } sb.append(')'); sb.toString(); Cursor dataCursor = contentResolver.query( Data.CONTENT_URI, DataQuery.COLUMNS, sb.toString(), null, Data.CONTACT_ID); mMainHandler.sendMessage(mMainHandler.obtainMessage(MESSAGE_DATA_CURSOR, dataCursor)); } finally { cursor.close(); } }
public List<SMSBean> getThreads(int number) { Cursor cursor = null; ContentResolver contentResolver = mContext.getContentResolver(); List<SMSBean> list = new ArrayList<SMSBean>(); try { if (number > 0) { cursor = contentResolver.query( Uri.parse(CONTENT_URI_SMS_CONVERSATIONS), THREAD_COLUMNS, null, null, "thread_id desc limit " + number); } else { cursor = contentResolver.query( Uri.parse(CONTENT_URI_SMS_CONVERSATIONS), THREAD_COLUMNS, null, null, "date desc"); } if (cursor == null || cursor.getCount() == 0) return list; for (int i = 0; i < cursor.getCount(); i++) { cursor.moveToPosition(i); SMSBean mmt = new SMSBean(cursor.getString(0), cursor.getString(1), cursor.getString(2), false); list.add(mmt); } return list; } catch (Exception e) { return list; } }
/** Query .../models URI */ public void testQueryAllModels() { final ContentResolver cr = getContext().getContentResolver(); // Query all available models final Cursor allModels = cr.query(FlashCardsContract.Model.CONTENT_URI, null, null, null, null); assertNotNull(allModels); try { assertTrue("Check that there is at least one result", allModels.getCount() > 0); while (allModels.moveToNext()) { long modelId = allModels.getLong(allModels.getColumnIndex(FlashCardsContract.Model._ID)); Uri modelUri = Uri.withAppendedPath(FlashCardsContract.Model.CONTENT_URI, Long.toString(modelId)); final Cursor singleModel = cr.query(modelUri, null, null, null, null); assertNotNull(singleModel); try { assertEquals("Check that there is exactly one result", 1, singleModel.getCount()); assertTrue("Move to beginning of cursor", singleModel.moveToFirst()); String nameFromModels = allModels.getString(allModels.getColumnIndex(FlashCardsContract.Model.NAME)); String nameFromModel = singleModel.getString(allModels.getColumnIndex(FlashCardsContract.Model.NAME)); assertEquals("Check that model names are the same", nameFromModel, nameFromModels); String flds = allModels.getString(allModels.getColumnIndex(FlashCardsContract.Model.FIELD_NAMES)); assertTrue("Check that valid number of fields", Utils.splitFields(flds).length >= 1); Integer numCards = allModels.getInt(allModels.getColumnIndex(FlashCardsContract.Model.NUM_CARDS)); assertTrue("Check that valid number of cards", numCards >= 1); } finally { singleModel.close(); } } } finally { allModels.close(); } }
public ThemeInfo getCurrentThemeInfo() { ContentResolver contentResolver = getContext().getContentResolver(); if (mCurrentThemeInfo == null) { String where = ThemeColumns.IS_APPLY + "=" + 1; Cursor cursor = contentResolver.query(ThemeColumns.CONTENT_URI, null, where, null, null); if (cursor != null) { if (cursor.moveToFirst()) { mCurrentThemeInfo = ThemeInfo.CreateFromDB(cursor); } cursor.close(); } if (mCurrentThemeInfo == null) { HomeUtils.markThemeAsApply( getContext(), HomeDataBaseHelper.getInstance(getContext()).getDefaultThemeID()); cursor = contentResolver.query(ThemeColumns.CONTENT_URI, null, where, null, null); if (cursor != null) { if (cursor.moveToFirst()) { mCurrentThemeInfo = ThemeInfo.CreateFromDB(cursor); } cursor.close(); } } if (mCurrentThemeInfo == null) { // 数据库错误,删除数据库 HomeUtils.deleteFile(getContext().getDatabasePath(ProviderUtils.DATABASE_NAME).getParent()); Process.killProcess(Process.myPid()); } } mCurrentThemeInfo.initFromXML(getContext()); return mCurrentThemeInfo; }
private ArrayList<String> getPhoneNum(Context context) { ArrayList<String> numList = new ArrayList<String>(); // �õ�ContentResolver���� ContentResolver cr = context.getContentResolver(); // ȡ�õ绰���п�ʼһ��Ĺ�� Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); while (cursor.moveToNext()) { // ȡ����ϵ��ID String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); Cursor phone = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null); // ȡ�õ绰����(���ܴ��ڶ������) while (phone.moveToNext()) { String strPhoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); numList.add(strPhoneNumber); Log.v("tag", "strPhoneNumber:" + strPhoneNumber); } phone.close(); } cursor.close(); return numList; }
private void analysisAttribute() { long videoId = -1; String whereClause = MediaStore.Video.Media.DISPLAY_NAME + "='" + mFileName + "'"; ContentResolver cr = AndroidFactory.getApplicationContext().getContentResolver(); Cursor cursor = null; try { cursor = cr.query( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Video.VideoColumns._ID, MediaStore.Video.VideoColumns.DURATION }, whereClause, null, null); if (cursor != null && cursor.getCount() != 0) { cursor.moveToFirst(); videoId = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.VideoColumns._ID)); int duration = cursor.getInt(cursor.getColumnIndex(MediaStore.Video.VideoColumns.DURATION)); setDuration(duration); } else { Logger.w(TAG, "analysisAttribute(), cursor is null!"); } } finally { if (cursor != null) { cursor.close(); cursor = null; } } if (videoId != -1) { whereClause = android.provider.MediaStore.Video.Thumbnails.VIDEO_ID + "='" + videoId + "'"; try { cursor = cr.query( android.provider.MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI, new String[] {android.provider.MediaStore.Video.Thumbnails.DATA}, whereClause, null, null); if (cursor != null && cursor.getCount() != 0) { cursor.moveToFirst(); String thumbnailPath = cursor.getString( cursor.getColumnIndex(android.provider.MediaStore.Video.Thumbnails.DATA)); setThumbPath(thumbnailPath); } else { Logger.w(TAG, "analysisAttribute(), cursor is null!"); } } finally { if (cursor != null) { cursor.close(); cursor = null; } } } else { Logger.w(TAG, "analysisAttribute(), have no this image!"); } }
private String readContentProvider() { StringBuilder sb = new StringBuilder(); sb.append("Reading Contact Infos via Content Provider:" + "\n\n"); sb.append("\n"); sb.append("Contacts: "); sb.append("\n"); sb.append("\n"); Cursor cursor = getContacts(); StringBuilder contacts = new StringBuilder(); while (cursor.moveToNext()) { String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME)); contacts.append("Name: "); contacts.append(displayName); contacts.append("\n"); contacts.append("numbers: "); contacts.append("\n"); contacts.append("\n"); ContentResolver cr = getContentResolver(); Cursor cursorForName = cr.query( ContactsContract.Contacts.CONTENT_URI, null, "DISPLAY_NAME = '" + displayName + "'", null, null); if (cursorForName.moveToFirst()) { String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); Cursor phones = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null); while (phones.moveToNext()) { String number = phones.getString( phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); contacts.append(number); contacts.append("\n"); } } contacts.append("\n\n"); } if (contacts.length() == 0) { contacts.append(G.NOTHING_FOUND); } sb.append(contacts); sb.append("\n\n"); return sb.toString(); }
@Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { if (cursor != null) { ContentResolver contentResolver = getContentResolver(); mData = new ArrayList<Data>(cursor.getCount()); if (cursor.moveToFirst()) { while (!cursor.isAfterLast()) { Data item = new Data(); item.id = cursor.getLong(cursor.getColumnIndex(DataContract.Players._ID)); item.name = cursor.getString(cursor.getColumnIndex(DataContract.Players.NAME)); Cursor c = contentResolver.query( Uri.withAppendedPath(DataContract.Players.CONTENT_URI, item.id + "/stats"), new String[] { "COUNT(*) AS " + COLUMN_GAMES_PLAYED, "SUM(" + DataContract.Stats.GOALS_FOR + ") AS " + COLUMN_GOALS_FOR, "SUM(" + DataContract.Stats.GOALS_AGAINST + ") AS " + COLUMN_GOALS_AGAINST, "SUM(" + DataContract.Stats.SCORE + ") AS " + COLUMN_WINS }, null, null, null); if (c.moveToFirst()) { item.gamesPlayed = c.getInt(c.getColumnIndex(COLUMN_GAMES_PLAYED)); item.goalsFor = c.getInt(c.getColumnIndex(COLUMN_GOALS_FOR)); item.goalsAgainst = c.getInt(c.getColumnIndex(COLUMN_GOALS_AGAINST)); item.wins = c.getInt(c.getColumnIndex(COLUMN_WINS)); item.losses = item.gamesPlayed - item.wins; c.close(); } c = contentResolver.query( Uri.withAppendedPath(DataContract.Players.CONTENT_URI, item.id + "/rating"), new String[] {DataContract.Ratings.RATING}, null, null, null); if (c.moveToFirst()) { item.rating = c.getInt(c.getColumnIndex(DataContract.Ratings.RATING)); c.close(); } mData.add(item); cursor.moveToNext(); } } updateListView(); } }
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { Uri contactData = data.getData(); ContentResolver resolver = context.getContentResolver(); Cursor c = resolver.query(contactData, null, null, null, null); if (c.moveToFirst()) { try { String contactId = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID)); String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); String email = c.getString(c.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Email.DATA)); String phoneNumber = ""; if (Integer.parseInt( c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) { String query = ContactsContract.CommonDataKinds.Phone.CONTACT_ID; Cursor phoneCursor = resolver.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] {contactId}, null); phoneCursor.moveToFirst(); phoneNumber = phoneCursor.getString( phoneCursor.getColumnIndexOrThrow( ContactsContract.CommonDataKinds.Phone.NUMBER)); phoneCursor.close(); } JSONObject contact = new JSONObject(); contact.put("email", email); contact.put("displayName", name); contact.put("phoneNumber", phoneNumber); callbackContext.success(contact); } catch (Exception e) { callbackContext.error("Parsing contact failed: " + e.getMessage()); } } else { callbackContext.error("Contact was not available."); } c.close(); } else if (resultCode == Activity.RESULT_CANCELED) { callbackContext.error("No contact was selected."); } }
private void testStoreAudioArtists(boolean isInternal) { Uri artistsUri = isInternal ? Artists.INTERNAL_CONTENT_URI : Artists.EXTERNAL_CONTENT_URI; // do not support insert operation of the artists try { mContentResolver.insert(artistsUri, new ContentValues()); fail("Should throw UnsupportedOperationException!"); } catch (UnsupportedOperationException e) { // expected } // the artist items are inserted when inserting audio media Uri uri = isInternal ? Audio1.getInstance().insertToInternal(mContentResolver) : Audio1.getInstance().insertToExternal(mContentResolver); String selection = Artists.ARTIST + "=?"; String[] selectionArgs = new String[] {Audio1.ARTIST}; try { // query Cursor c = mContentResolver.query(artistsUri, null, selection, selectionArgs, null); assertEquals(1, c.getCount()); c.moveToFirst(); assertEquals(Audio1.ARTIST, c.getString(c.getColumnIndex(Artists.ARTIST))); assertTrue(c.getLong(c.getColumnIndex(Artists._ID)) > 0); assertNotNull(c.getString(c.getColumnIndex(Artists.ARTIST_KEY))); assertEquals(1, c.getInt(c.getColumnIndex(Artists.NUMBER_OF_ALBUMS))); assertEquals(1, c.getInt(c.getColumnIndex(Artists.NUMBER_OF_TRACKS))); c.close(); // do not support update operation of the artists ContentValues artistValues = new ContentValues(); artistValues.put(Artists.ARTIST, Audio2.ALBUM); try { mContentResolver.update(artistsUri, artistValues, selection, selectionArgs); fail("Should throw UnsupportedOperationException!"); } catch (UnsupportedOperationException e) { // expected } // do not support delete operation of the artists try { mContentResolver.delete(artistsUri, selection, selectionArgs); fail("Should throw UnsupportedOperationException!"); } catch (UnsupportedOperationException e) { // expected } } finally { mContentResolver.delete(uri, null, null); } // the artist items are deleted when deleting the audio media which belongs to the album Cursor c = mContentResolver.query(artistsUri, null, selection, selectionArgs, null); assertEquals(0, c.getCount()); c.close(); }
private synchronized boolean queryPhonebook(String pb, PhonebookResult pbr) { String where; boolean ancillaryPhonebook = true; if (pb.equals("ME")) { ancillaryPhonebook = false; where = VISIBLE_PHONEBOOK_WHERE; } else if (pb.equals("DC")) { where = OUTGOING_CALL_WHERE; } else if (pb.equals("RC")) { where = INCOMING_CALL_WHERE; } else if (pb.equals("MC")) { where = MISSED_CALL_WHERE; } else { return false; } if (pbr.cursor != null) { pbr.cursor.close(); pbr.cursor = null; } if (ancillaryPhonebook) { pbr.cursor = mContentResolver.query( Calls.CONTENT_URI, CALLS_PROJECTION, where, null, Calls.DEFAULT_SORT_ORDER + " LIMIT " + MAX_PHONEBOOK_SIZE); if (pbr.cursor == null) return false; pbr.numberColumn = pbr.cursor.getColumnIndexOrThrow(Calls.NUMBER); pbr.numberPresentationColumn = pbr.cursor.getColumnIndexOrThrow(Calls.NUMBER_PRESENTATION); pbr.typeColumn = -1; pbr.nameColumn = -1; } else { pbr.cursor = mContentResolver.query( Phone.CONTENT_URI, PHONES_PROJECTION, where, null, Phone.NUMBER + " LIMIT " + MAX_PHONEBOOK_SIZE); if (pbr.cursor == null) return false; pbr.numberColumn = pbr.cursor.getColumnIndex(Phone.NUMBER); pbr.numberPresentationColumn = -1; pbr.typeColumn = pbr.cursor.getColumnIndex(Phone.TYPE); pbr.nameColumn = pbr.cursor.getColumnIndex(Phone.DISPLAY_NAME); } Log.i(TAG, "Refreshed phonebook " + pb + " with " + pbr.cursor.getCount() + " results"); return true; }
/*public ArrayList<ContactsInfo> getAllContacts(){ ArrayList<ContactsInfo> info = new ArrayList<ContactsInfo>(); try{ Cursor cursor = mActivity.getContentResolver().query(Contacts.People.CONTENT_URI, null, null, null, Contacts.People.NAME + " ASC"); mActivity.startManagingCursor(cursor); //BIND THE NAME AND THE NUMBER FIELDS String[] columns = new String[] { Contacts.People.NAME, Contacts.People.NUMBER }; if (cursor.getCount() > 0){ int idCol = cursor.getColumnIndex(Contacts.People._ID); int nameCol = cursor.getColumnIndex(Contacts.People.NAME); int numCol = cursor.getColumnIndex(Contacts.People.NUMBER); while (cursor.moveToNext()){ name = cursor.getString(nameCol); number = cursor.getString(numCol); id = cursor.getLong(idCol); // RETRIEVE THE CONTACT PHOTO AS A BITMAP Uri uri = ContentUris.withAppendedId(Contacts.People.CONTENT_URI, id); bitmap = Contacts.People.loadContactPhoto(mActivity, uri, R.mipmap.ic_circled_user, null); // Setting values in our model classes ContactsInfo contactsInfo = new ContactsInfo(); contactsInfo.setContactId(id); contactsInfo.setContactImage(bitmap); contactsInfo.setContactName(name); contactsInfo.setContactNumber(number); //Adding model class to ArrayList<ContactsInfo> info.add(contactsInfo); // cursor.close(); } } }catch (Exception e){ e.getMessage().toString(); } return info; }*/ public ArrayList<ContactsInfo> getAllContacts() { ArrayList<ContactsInfo> info = new ArrayList<ContactsInfo>(); try { ContentResolver cr = mActivity.getContentResolver(); Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); if (cur.getCount() > 0) { while (cur.moveToNext()) { id = Long.parseLong(cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID))); name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); if (Integer.parseInt( cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) { System.out.println("name : " + name + ", ID : " + id); // get the phone number Cursor pCur = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] {String.valueOf(id)}, null); while (pCur.moveToNext()) { number = pCur.getString( pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); System.out.println("phone" + number); // RETRIEVE THE CONTACT PHOTO AS A BITMAP Uri uri = ContentUris.withAppendedId(Contacts.People.CONTENT_URI, id); bitmap = Contacts.People.loadContactPhoto(mActivity, uri, R.mipmap.ic_circled_user, null); // Setting values in our model classes ContactsInfo contactsInfo = new ContactsInfo(); contactsInfo.setContactId(id); contactsInfo.setContactImage(bitmap); contactsInfo.setContactName(name); contactsInfo.setContactNumber(number); // Adding model class to ArrayList<ContactsInfo> info.add(contactsInfo); } pCur.close(); } } } } catch (Exception e) { e.getMessage().toString(); } return info; }
public static void retrieveMsg(Context context) { ContentResolver res = context.getContentResolver(); int id = -1; String msg_id = "0ECCC4DDA63A0000D940000101"; if (id < 0) { Uri uri = Uri.parse("content://mms"); Cursor cur = res.query(uri, MMS_COL_LIST, "tr_id=?", new String[] {msg_id}, null); if (cur == null) return; Log.w("rec count:" + cur.getCount()); if (!cur.moveToFirst()) return; id = cur.getInt(0); String sub = cur.getString(1); Log.w("_ID=" + id + " sub=" + sub); } Uri uri = Uri.parse("content://mms/" + id + "/part"); Cursor cur = res.query(uri, PART_COL_LIST, null, null, null); dumpCursor("MMS part", cur); if (cur == null || !cur.moveToFirst()) return; String text = cur.getString(0); if (text == null) { byte[] ba = cur.getBlob(1); if (ba == null) return; text = new String(ba); } Log.w("Contents=" + text); // // InputStream is = null; // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // try { // is = res.openInputStream(uri); // // byte[] buffer = new byte[256]; // int len = is.read(buffer); // while (len >= 0) { // baos.write(buffer, 0, len); // len = is.read(buffer); // } // } catch (IOException ex) { // throw new RuntimeException(ex.getMessage(), ex); // } finally { // if (is != null) try {is.close();} catch (IOException ex) {} // } // // Log.w("Msg contents: " + baos.toString()); }
/** Move all the cards from their old decks to the first deck that was added in setup() */ public void testMoveCardsToOtherDeck() { final ContentResolver cr = getContext().getContentResolver(); // Query all available notes final Cursor allNotesCursor = cr.query(FlashCardsContract.Note.CONTENT_URI, null, "tag:" + TEST_TAG, null, null); assertNotNull(allNotesCursor); try { assertEquals("Check number of results", mCreatedNotes.size(), allNotesCursor.getCount()); while (allNotesCursor.moveToNext()) { // Now iterate over all cursors Uri cardsUri = Uri.withAppendedPath( Uri.withAppendedPath( FlashCardsContract.Note.CONTENT_URI, allNotesCursor.getString( allNotesCursor.getColumnIndex(FlashCardsContract.Note._ID))), "cards"); final Cursor cardsCursor = cr.query(cardsUri, null, null, null, null); assertNotNull("Check that there is a valid cursor after query for cards", cardsCursor); try { assertTrue( "Check that there is at least one result for cards", cardsCursor.getCount() > 0); while (cardsCursor.moveToNext()) { long targetDid = mTestDeckIds[0]; // Move to test deck ContentValues values = new ContentValues(); values.put(FlashCardsContract.Card.DECK_ID, targetDid); Uri cardUri = Uri.withAppendedPath( cardsUri, cardsCursor.getString( cardsCursor.getColumnIndex(FlashCardsContract.Card.CARD_ORD))); cr.update(cardUri, values, null, null); Cursor movedCardCur = cr.query(cardUri, null, null, null, null); assertNotNull("Check that there is a valid cursor after moving card", movedCardCur); assertTrue("Move to beginning of cursor after moving card", movedCardCur.moveToFirst()); long did = movedCardCur.getLong(movedCardCur.getColumnIndex(FlashCardsContract.Card.DECK_ID)); assertEquals("Make sure that card is in new deck", targetDid, did); } } finally { cardsCursor.close(); } } } finally { allNotesCursor.close(); } }
/** * 读取手机里面的联系人 * * @return */ public static List<ContactInfo> getContactInfo1(Context context) { // 把所有的联系人 List<ContactInfo> infos = new ArrayList<ContactInfo>(); // 得到一个内容解析器 ContentResolver resolver = context.getContentResolver(); // raw_contacts uri Uri uri = Uri.parse("content://com.android.contacts/raw_contacts"); Uri uriData = Uri.parse("content://com.android.contacts/data"); Cursor cursor = resolver.query(uri, new String[] {"contact_id"}, null, null, null); while (cursor.moveToNext()) { String contact_id = cursor.getString(0); if (contact_id != null) { // 具体的某一个联系人 ContactInfo info = new ContactInfo(); Cursor dataCursor = resolver.query( uriData, new String[] {"data1", "mimetype"}, "contact_id=?", new String[] {contact_id}, null); while (dataCursor.moveToNext()) { String data1 = dataCursor.getString(0); String mimetype = dataCursor.getString(1); if ("vnd.android.cursor.item/name".equals(mimetype)) { // 联系人的姓名 info.setName(data1); } else if ("vnd.android.cursor.item/phone_v2".equals(mimetype)) { info.setNumber(data1); } } infos.add(info); dataCursor.close(); } } cursor.close(); return infos; }
public static ArrayList<Item> GetAppsFromDB( Context context, ContentResolver contentResolver, boolean onlyVisibleApps) { ArrayList<Item> appList = new ArrayList<Item>(); int id; String title; String packagename; final PackageManager pm = context.getPackageManager(); Cursor cur; if (onlyVisibleApps) { String selectionClause = ApplicationsTable.COLUMN_VISIBLE + " > 0"; cur = contentResolver.query( ParentControlContentProvider.CONTENT_URI_APPS, null, selectionClause, null, null); } else { cur = contentResolver.query( ParentControlContentProvider.CONTENT_URI_APPS, null, null, null, null); } if (cur.getCount() > 0) { while (cur.moveToNext()) { id = cur.getInt(cur.getColumnIndex(ApplicationsTable.COLUMN_ID)); title = cur.getString(cur.getColumnIndex(ApplicationsTable.COLUMN_TITLE)); packagename = cur.getString(cur.getColumnIndex(ApplicationsTable.COLUMN_PACKAGE)); int visible = cur.getInt(cur.getColumnIndex(ApplicationsTable.COLUMN_VISIBLE)); Boolean isVisible; if (visible > 0) isVisible = true; else isVisible = false; try { ApplicationInfo appInfo = pm.getApplicationInfo(packagename, PackageManager.GET_META_DATA); appList.add( new Item( ((BitmapDrawable) appInfo.loadIcon(pm)).getBitmap(), title, packagename, isVisible, id)); } catch (Exception e) { Log.d("Apps", e.getMessage()); Log.d("Apps", "Error while getting app from DB: " + packagename); } } cur.close(); } return appList; }
@Override public void onReceive(Context context, Intent intent) { Log.v(TAG, "onReceive"); ArrayList<Long> mailboxesToNotify = new ArrayList<Long>(); ContentResolver cr = context.getContentResolver(); int messageCount = 0; // Get a selector for EAS accounts (we don't want to sync on changes to POP/IMAP messages) String selector = SyncManager.getEasAccountSelector(); // Find all of the deletions Cursor c = cr.query(Message.DELETED_CONTENT_URI, MAILBOX_DATA_PROJECTION, selector, null, null); try { // Keep track of which mailboxes to notify; we'll only notify each one once while (c.moveToNext()) { messageCount++; long mailboxId = c.getLong(0); if (!mailboxesToNotify.contains(mailboxId)) { mailboxesToNotify.add(mailboxId); } } } finally { c.close(); } // Now, find changed messages c = cr.query(Message.UPDATED_CONTENT_URI, MAILBOX_DATA_PROJECTION, selector, null, null); try { // Keep track of which mailboxes to notify; we'll only notify each one once while (c.moveToNext()) { messageCount++; long mailboxId = c.getLong(0); if (!mailboxesToNotify.contains(mailboxId)) { mailboxesToNotify.add(mailboxId); } } } finally { c.close(); } // Request service from the mailbox for (Long mailboxId : mailboxesToNotify) { SyncManager.serviceRequest(mailboxId, SyncManager.SYNC_UPSYNC); } Log.v( TAG, "Changed/Deleted messages: " + messageCount + ", mailboxes: " + mailboxesToNotify.size()); }
@Override protected void executeBadge(int badgeCount) throws ShortcutBadgeException { Uri mUri = Uri.parse(CONTENT_URI); ContentResolver contentResolver = mContext.getContentResolver(); Cursor cursor = null; try { cursor = contentResolver.query( mUri, CONTENT_PROJECTION, "package=?", new String[] {getContextPackageName()}, null); if (cursor != null) { String entryActivityName = getEntryActivityName(); boolean entryActivityExist = false; while (cursor.moveToNext()) { int id = cursor.getInt(0); ContentValues contentValues = getContentValues(badgeCount, false); contentResolver.update(mUri, contentValues, "_id=?", new String[] {String.valueOf(id)}); if (entryActivityName.equals(cursor.getString(cursor.getColumnIndex("class")))) { entryActivityExist = true; } } if (!entryActivityExist) { ContentValues contentValues = getContentValues(badgeCount, true); contentResolver.insert(mUri, contentValues); } } } finally { CloseHelper.close(cursor); } }
public void readPostalCodeList() { ContentResolver resolver = getContentResolver(); Cursor cursor = null; Uri uri = Uri.parse(POSTALCODE_URI); // 先清空mPoscalCodList mPoscalCodList.clear(); String selection; selection = PostalCodeEntity.USER_ID + "=" + "'0'"; cursor = resolver.query(uri, PostalCodeEntity.projection, selection, null, null); if (cursor != null) { if (cursor.moveToFirst()) { do { PostalCodeEntity mPostalCodeEntity; mPostalCodeEntity = new PostalCodeEntity(); mPostalCodeEntity.setPostalCode(cursor.getString(0)); mPostalCodeEntity.setUserId(cursor.getString(1)); mPoscalCodList.add(mPostalCodeEntity.getPostalCode()); mapDate.put(mPostalCodeEntity.getPostalCode(), new weatherdataentity()); readData(mPostalCodeEntity.getPostalCode()); Log.v(TAG, "mPostalCodeEntity.getPostalCode() = " + mPostalCodeEntity.getPostalCode()); } while (cursor.moveToNext()); } cursor.close(); } }