android.provider.ContactsContract.Contacts Java Examples

The following examples show how to use android.provider.ContactsContract.Contacts. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ContactsUtils5.java    From CSipSimple with GNU General Public License v3.0 6 votes vote down vote up
@Override
public List<String> getCSipPhonesByGroup(Context ctxt, String groupName) {

    Cursor contacts = getContactsByGroup(ctxt, groupName);
    ArrayList<String> results = new ArrayList<String>();
    if (contacts != null) {
        try {
            while (contacts.moveToNext()) {
                List<String> res = getCSipPhonesContact(ctxt, contacts.getLong(contacts
                        .getColumnIndex(Contacts._ID)));
                results.addAll(res);
            }
        } catch (Exception e) {
            Log.e(THIS_FILE, "Error while looping on contacts", e);
        } finally {
            contacts.close();
        }
    }
    return results;
}
 
Example #2
Source File: DisplayActivity.java    From coursera-android with MIT License 6 votes vote down vote up
private void addRecordToBatchInsertOperation(String name,
                                             List<ContentProviderOperation> ops) {

    int position = ops.size();

    // First part of operation
    ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
            .withValue(RawContacts.ACCOUNT_TYPE, mType)
            .withValue(RawContacts.ACCOUNT_NAME, mName)
            .withValue(Contacts.STARRED, 1).build());

    // Second part of operation
    ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
            .withValueBackReference(Data.RAW_CONTACT_ID, position)
            .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
            .withValue(StructuredName.DISPLAY_NAME, name).build());

}
 
Example #3
Source File: LogEntryAdapter.java    From emerald-dialer with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onClick(View view) {
	if (view.getId() == R.id.contact_image) {
		String number = (String)view.getTag();
		if (null == number) {
			return;
		}
		Uri contactIdUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
		Cursor cursor = activityRef.get().getContentResolver().query(contactIdUri, new String[] {PhoneLookup.CONTACT_ID}, null, null, null);
		if (cursor == null || !cursor.moveToFirst()) {
			unknownNumberDialog(number);
			return;
		}
		String contactId = cursor.getString(0);
		cursor.close();
		Intent intent = new Intent(Intent.ACTION_VIEW);
		Uri uri = Uri.withAppendedPath(Contacts.CONTENT_URI, contactId);
		intent.setDataAndType(uri, "vnd.android.cursor.dir/contact");
		try {
			activityRef.get().startActivity(intent);
		} catch (ActivityNotFoundException e) {
			activityRef.get().showMissingContactsAppDialog();
		}
	}
}
 
Example #4
Source File: ApiElevenPlus.java    From Linphone4Android with GNU General Public License v3.0 6 votes vote down vote up
public static Intent prepareAddContactIntent(String displayName, String sipUri) {
	Intent intent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI);
	intent.putExtra(Insert.NAME, displayName);
	
	if (sipUri != null && sipUri.startsWith("sip:")) {
		sipUri = sipUri.substring(4);
	}
	
	ArrayList<ContentValues> data = new ArrayList<ContentValues>();
	ContentValues sipAddressRow = new ContentValues();
	sipAddressRow.put(Contacts.Data.MIMETYPE, SipAddress.CONTENT_ITEM_TYPE);
	sipAddressRow.put(SipAddress.SIP_ADDRESS, sipUri);
	data.add(sipAddressRow);
	intent.putParcelableArrayListExtra(Insert.DATA, data);
	
	return intent;
}
 
Example #5
Source File: ContactsBinaryDictionary.java    From openboard with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Loads data within content providers to the dictionary.
 */
private void loadDictionaryForUriLocked(final Uri uri) {
    if (!PermissionsUtil.checkAllPermissionsGranted(
            mContext, Manifest.permission.READ_CONTACTS)) {
        Log.i(TAG, "No permission to read contacts. Not loading the Dictionary.");
    }

    final ArrayList<String> validNames = mContactsManager.getValidNames(uri);
    for (final String name : validNames) {
        addNameLocked(name);
    }
    if (uri.equals(Contacts.CONTENT_URI)) {
        // Since we were able to add content successfully, update the local
        // state of the manager.
        mContactsManager.updateLocalState(validNames);
    }
}
 
Example #6
Source File: CursorFragment.java    From V.FlyoutTest with MIT License 6 votes vote down vote up
@Override public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // Give some text to display if there is no data.  In a real
    // application this would come from a resource.
    setEmptyText("No phone numbers");

    // We have a menu item to show in action bar.
    setHasOptionsMenu(true);

    // Create an empty adapter we will use to display the loaded data.
    mAdapter = new SimpleCursorAdapter(getActivity(),
            android.R.layout.simple_list_item_2, null,
            new String[] { Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS },
            new int[] { android.R.id.text1, android.R.id.text2 }, 0);
    setListAdapter(mAdapter);

    // Start out with a progress indicator.
    setListShown(false);

    // Prepare the loader.  Either re-connect with an existing one,
    // or start a new one.
    getLoaderManager().initLoader(0, null, this);
}
 
Example #7
Source File: ContactAccessor.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public String getNameFromContact(Context context, Uri uri) {
  Cursor cursor = null;

  try {
    cursor = context.getContentResolver().query(uri, new String[] {Contacts.DISPLAY_NAME},
                                                null, null, null);

    if (cursor != null && cursor.moveToFirst())
      return cursor.getString(0);

  } finally {
    if (cursor != null)
      cursor.close();
  }

  return null;
}
 
Example #8
Source File: ContactsContentObserver.java    From Indic-Keyboard with Apache License 2.0 6 votes vote down vote up
public void registerObserver(final ContactsChangedListener listener) {
    if (!PermissionsUtil.checkAllPermissionsGranted(
            mContext, Manifest.permission.READ_CONTACTS)) {
        Log.i(TAG, "No permission to read contacts. Not registering the observer.");
        // do nothing if we do not have the permission to read contacts.
        return;
    }

    if (DebugFlags.DEBUG_ENABLED) {
        Log.d(TAG, "registerObserver()");
    }
    mContactsChangedListener = listener;
    mContentObserver = new ContentObserver(null /* handler */) {
        @Override
        public void onChange(boolean self) {
            ExecutorUtils.getBackgroundExecutor(ExecutorUtils.KEYBOARD)
                    .execute(ContactsContentObserver.this);
        }
    };
    final ContentResolver contentResolver = mContext.getContentResolver();
    contentResolver.registerContentObserver(Contacts.CONTENT_URI, true, mContentObserver);
}
 
Example #9
Source File: ValidateNotificationPeople.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public void mergeContact(Cursor cursor) {
    mAffinity = Math.max(mAffinity, VALID_CONTACT);

    // Contact ID
    int id;
    final int idIdx = cursor.getColumnIndex(Contacts._ID);
    if (idIdx >= 0) {
        id = cursor.getInt(idIdx);
        if (DEBUG) Slog.d(TAG, "contact _ID is: " + id);
    } else {
        id = -1;
        Slog.i(TAG, "invalid cursor: no _ID");
    }

    // Starred
    final int starIdx = cursor.getColumnIndex(Contacts.STARRED);
    if (starIdx >= 0) {
        boolean isStarred = cursor.getInt(starIdx) != 0;
        if (isStarred) {
            mAffinity = Math.max(mAffinity, STARRED_CONTACT);
        }
        if (DEBUG) Slog.d(TAG, "contact STARRED is: " + isStarred);
    } else {
        if (DEBUG) Slog.d(TAG, "invalid cursor: no STARRED");
    }
}
 
Example #10
Source File: ValidateNotificationPeople.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public void initialize(Context context, NotificationUsageStats usageStats) {
    if (DEBUG) Slog.d(TAG, "Initializing  " + getClass().getSimpleName() + ".");
    mUserToContextMap = new ArrayMap<>();
    mBaseContext = context;
    mUsageStats = usageStats;
    mPeopleCache = new LruCache<String, LookupResult>(PEOPLE_CACHE_SIZE);
    mEnabled = ENABLE_PEOPLE_VALIDATOR && 1 == Settings.Global.getInt(
            mBaseContext.getContentResolver(), SETTING_ENABLE_PEOPLE_VALIDATOR, 1);
    if (mEnabled) {
        mHandler = new Handler();
        mObserver = new ContentObserver(mHandler) {
            @Override
            public void onChange(boolean selfChange, Uri uri, int userId) {
                super.onChange(selfChange, uri, userId);
                if (DEBUG || mEvictionCount % 100 == 0) {
                    if (VERBOSE) Slog.i(TAG, "mEvictionCount: " + mEvictionCount);
                }
                mPeopleCache.evictAll();
                mEvictionCount++;
            }
        };
        mBaseContext.getContentResolver().registerContentObserver(Contacts.CONTENT_URI, true,
                mObserver, UserHandle.USER_ALL);
    }
}
 
Example #11
Source File: ContactIdentityManagerICS.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Uri getSelfIdentityUri() {
  String[] PROJECTION = new String[] {
      PhoneLookup.DISPLAY_NAME,
      PhoneLookup.LOOKUP_KEY,
      PhoneLookup._ID,
  };

  Cursor cursor = null;

  try {
    cursor = context.getContentResolver().query(ContactsContract.Profile.CONTENT_URI,
                                                  PROJECTION, null, null, null);

    if (cursor != null && cursor.moveToFirst()) {
      return Contacts.getLookupUri(cursor.getLong(2), cursor.getString(1));
    }
  } finally {
    if (cursor != null)
      cursor.close();
  }

  return null;
}
 
Example #12
Source File: Gallery2.java    From codeexamples-android with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gallery_2);

    // Get a cursor with all people
    Cursor c = getContentResolver().query(Contacts.CONTENT_URI,
            CONTACT_PROJECTION, null, null, null);
    startManagingCursor(c);

    SpinnerAdapter adapter = new SimpleCursorAdapter(this,
    // Use a template that displays a text view
            android.R.layout.simple_gallery_item,
            // Give the cursor to the list adatper
            c,
            // Map the NAME column in the people database to...
            new String[] {Contacts.DISPLAY_NAME},
            // The "text1" view defined in the XML template
            new int[] { android.R.id.text1 });

    Gallery g = (Gallery) findViewById(R.id.gallery);
    g.setAdapter(adapter);
}
 
Example #13
Source File: ContactsContentObserver.java    From openboard with GNU General Public License v3.0 6 votes vote down vote up
public void registerObserver(final ContactsChangedListener listener) {
    if (!PermissionsUtil.checkAllPermissionsGranted(
            mContext, Manifest.permission.READ_CONTACTS)) {
        Log.i(TAG, "No permission to read contacts. Not registering the observer.");
        // do nothing if we do not have the permission to read contacts.
        return;
    }

    if (DebugFlags.DEBUG_ENABLED) {
        Log.d(TAG, "registerObserver()");
    }
    mContactsChangedListener = listener;
    mContentObserver = new ContentObserver(null /* handler */) {
        @Override
        public void onChange(boolean self) {
            ExecutorUtils.getBackgroundExecutor(ExecutorUtils.KEYBOARD)
                    .execute(ContactsContentObserver.this);
        }
    };
    final ContentResolver contentResolver = mContext.getContentResolver();
    contentResolver.registerContentObserver(Contacts.CONTENT_URI, true, mContentObserver);
}
 
Example #14
Source File: ContactsListActivity.java    From coursera-android with MIT License 6 votes vote down vote up
private void loadContacts() {

        // Contact data
        String columnsToExtract[] = new String[] { Contacts._ID,
                Contacts.DISPLAY_NAME, Contacts.PHOTO_THUMBNAIL_URI };

        // Get the ContentResolver
        ContentResolver contentResolver = getContentResolver();

        // filter contacts with empty names
        String whereClause = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
                + Contacts.DISPLAY_NAME + " != '' ) AND (" + Contacts.STARRED
                + "== 1))";

        // sort by increasing ID
        String sortOrder = Contacts._ID + " ASC";

        // query contacts ContentProvider
        mCursor = contentResolver.query(Contacts.CONTENT_URI,
                columnsToExtract, whereClause, null, sortOrder);

        // pass mCursor to custom list adapter
        setListAdapter(new ContactInfoListAdapter(this, R.layout.list_item,
                mCursor, 0));

    }
 
Example #15
Source File: DialtactsActivity.java    From coursera-android with MIT License 6 votes vote down vote up
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.dialtacts_options, menu);

    // set up intents and onClick listeners
    final MenuItem callSettingsMenuItem = menu.findItem(R.id.menu_call_settings);
    final MenuItem searchMenuItem = menu.findItem(R.id.search_on_action_bar);
    final MenuItem filterOptionMenuItem = menu.findItem(R.id.filter_option);
    final MenuItem addContactOptionMenuItem = menu.findItem(R.id.add_contact);

    callSettingsMenuItem.setIntent(DialtactsActivity.getCallSettingsIntent());
    searchMenuItem.setOnMenuItemClickListener(mSearchMenuItemClickListener);
    filterOptionMenuItem.setOnMenuItemClickListener(mFilterOptionsMenuItemClickListener);
    addContactOptionMenuItem.setIntent(
            new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI));

    return true;
}
 
Example #16
Source File: ContactsUtils5.java    From CSipSimple with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Intent getAddContactIntent(String displayName, String csipUri) {
    Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT, Contacts.CONTENT_URI);
    intent.setType(Contacts.CONTENT_ITEM_TYPE);

    if (!TextUtils.isEmpty(displayName)) {
        intent.putExtra(Insert.NAME, displayName);
    }

    if (!TextUtils.isEmpty(csipUri)) {
        ArrayList<ContentValues> data = new ArrayList<ContentValues>();
        ContentValues csipProto = new ContentValues();
        csipProto.put(Data.MIMETYPE, CommonDataKinds.Im.CONTENT_ITEM_TYPE);
        csipProto.put(CommonDataKinds.Im.PROTOCOL, CommonDataKinds.Im.PROTOCOL_CUSTOM);
        csipProto.put(CommonDataKinds.Im.CUSTOM_PROTOCOL, SipManager.PROTOCOL_CSIP);
        csipProto.put(CommonDataKinds.Im.DATA, SipUri.getCanonicalSipContact(csipUri, false));
        data.add(csipProto);

        intent.putParcelableArrayListExtra(Insert.DATA, data);
    }

    return intent;
}
 
Example #17
Source File: ContactsUtils5.java    From CSipSimple with GNU General Public License v3.0 6 votes vote down vote up
@Override
public ContactInfo getContactInfo(Context context, Cursor cursor) {
    ContactInfo ci = new ContactInfo();
    // Get values
    ci.displayName = cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME));
    ci.contactId = cursor.getLong(cursor.getColumnIndex(Contacts._ID));
    ci.callerInfo.contactContentUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, ci.contactId);
    ci.callerInfo.photoId = cursor.getLong(cursor.getColumnIndex(Contacts.PHOTO_ID));
    int photoUriColIndex = cursor.getColumnIndex(Contacts.PHOTO_ID);
    ci.status = cursor.getString(cursor.getColumnIndex(Contacts.CONTACT_STATUS));
    ci.presence = cursor.getInt(cursor.getColumnIndex(Contacts.CONTACT_PRESENCE));

    if (photoUriColIndex >= 0) {
        String photoUri = cursor.getString(photoUriColIndex);
        if (!TextUtils.isEmpty(photoUri)) {
            ci.callerInfo.photoUri = Uri.parse(photoUri);
        }
    }
    ci.hasPresence = !TextUtils.isEmpty(ci.status);
    return ci;
}
 
Example #18
Source File: ContactsUtils14.java    From CSipSimple with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Bitmap getContactPhoto(Context ctxt, Uri uri, boolean hiRes, Integer defaultResource) {
    Bitmap img = null;
    InputStream s = Contacts.openContactPhotoInputStream(
            ctxt.getContentResolver(), uri, hiRes);
    img = BitmapFactory.decodeStream(s);

    if (img == null && defaultResource != null) {
        BitmapDrawable drawableBitmap = ((BitmapDrawable) ctxt.getResources().getDrawable(
                defaultResource));
        if (drawableBitmap != null) {
            img = drawableBitmap.getBitmap();
        }
    }
    return img;
}
 
Example #19
Source File: ContactsManagerTest.java    From Indic-Keyboard with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetValidNames() {
    final String contactName1 = "firstname last-name";
    final String contactName2 = "larry";
    mMatrixCursor.addRow(new Object[] { 1, contactName1, 0, 0, 0 });
    mMatrixCursor.addRow(new Object[] { 2, null /* null name */, 0, 0, 0 });
    mMatrixCursor.addRow(new Object[] { 3, contactName2, 0, 0, 0 });
    mMatrixCursor.addRow(new Object[] { 4, "[email protected]" /* invalid name */, 0, 0, 0 });
    mMatrixCursor.addRow(new Object[] { 5, "news-group" /* invalid name */, 0, 0, 0 });
    mFakeContactsContentProvider.addQueryResult(Contacts.CONTENT_URI, mMatrixCursor);

    final ArrayList<String> validNames = mManager.getValidNames(Contacts.CONTENT_URI);
    assertEquals(2, validNames.size());
    assertEquals(contactName1, validNames.get(0));
    assertEquals(contactName2, validNames.get(1));
}
 
Example #20
Source File: DisplayActivity.java    From coursera-android with MIT License 6 votes vote down vote up
private void addRecordToBatchInsertOperation(String name,
		List<ContentProviderOperation> ops) {

	int position = ops.size();

	// First part of operation
	ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
			.withValue(RawContacts.ACCOUNT_TYPE, mType)
			.withValue(RawContacts.ACCOUNT_NAME, mName)
			.withValue(Contacts.STARRED, 1).build());

	// Second part of operation
	ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
			.withValueBackReference(Data.RAW_CONTACT_ID, position)
			.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
			.withValue(StructuredName.DISPLAY_NAME, name).build());

}
 
Example #21
Source File: LoaderCursor.java    From codeexamples-android with Eclipse Public License 1.0 6 votes vote down vote up
@Override public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // Give some text to display if there is no data.  In a real
    // application this would come from a resource.
    setEmptyText("No phone numbers");

    // We have a menu item to show in action bar.
    setHasOptionsMenu(true);

    // Create an empty adapter we will use to display the loaded data.
    mAdapter = new SimpleCursorAdapter(getActivity(),
            android.R.layout.simple_list_item_2, null,
            new String[] { Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS },
            new int[] { android.R.id.text1, android.R.id.text2 }, 0);
    setListAdapter(mAdapter);

    // Start out with a progress indicator.
    setListShown(false);

    // Prepare the loader.  Either re-connect with an existing one,
    // or start a new one.
    getLoaderManager().initLoader(0, null, this);
}
 
Example #22
Source File: ContactsManager.java    From AOSP-Kayboard-7.1.2 with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the number of contacts in contacts content provider.
 */
public int getContactCount() {
    // TODO: consider switching to a rawQuery("select count(*)...") on the database if
    // performance is a bottleneck.
    Cursor cursor = null;
    try {
        cursor = mContext.getContentResolver().query(Contacts.CONTENT_URI,
                ContactsDictionaryConstants.PROJECTION_ID_ONLY, null, null, null);
        if (null == cursor) {
            return 0;
        }
        return cursor.getCount();
    } catch (final SQLiteException e) {
        Log.e(TAG, "SQLiteException in the remote Contacts process.", e);
    } finally {
        if (null != cursor) {
            cursor.close();
        }
    }
    return 0;
}
 
Example #23
Source File: CursorFragment.java    From V.FlyoutTest with MIT License 6 votes vote down vote up
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    // This is called when a new Loader needs to be created.  This
    // sample only has one Loader, so we don't care about the ID.
    // First, pick the base URI to use depending on whether we are
    // currently filtering.
    Uri baseUri;
    if (mCurFilter != null) {
        baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
                Uri.encode(mCurFilter));
    } else {
        baseUri = Contacts.CONTENT_URI;
    }

    // Now create and return a CursorLoader that will take care of
    // creating a Cursor for the data being displayed.
    String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
            + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
            + Contacts.DISPLAY_NAME + " != '' ))";
    return new CursorLoader(getActivity(), baseUri,
            CONTACTS_SUMMARY_PROJECTION, select, null,
            Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
}
 
Example #24
Source File: ContactsContentObserver.java    From AOSP-Kayboard-7.1.2 with Apache License 2.0 6 votes vote down vote up
public void registerObserver(final ContactsChangedListener listener) {
    if (!PermissionsUtil.checkAllPermissionsGranted(
            mContext, Manifest.permission.READ_CONTACTS)) {
        Log.i(TAG, "No permission to read contacts. Not registering the observer.");
        // do nothing if we do not have the permission to read contacts.
        return;
    }

    if (DebugFlags.DEBUG_ENABLED) {
        Log.d(TAG, "registerObserver()");
    }
    mContactsChangedListener = listener;
    mContentObserver = new ContentObserver(null /* handler */) {
        @Override
        public void onChange(boolean self) {
            ExecutorUtils.getBackgroundExecutor(ExecutorUtils.KEYBOARD)
                    .execute(ContactsContentObserver.this);
        }
    };
    final ContentResolver contentResolver = mContext.getContentResolver();
    contentResolver.registerContentObserver(Contacts.CONTENT_URI, true, mContentObserver);
}
 
Example #25
Source File: ContactsManagerTest.java    From Indic-Keyboard with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetValidNamesAffinity() {
    final long now = System.currentTimeMillis();
    final long month_ago = now - TimeUnit.MILLISECONDS.convert(31, TimeUnit.DAYS);
    for (int i = 0; i < ContactsManager.MAX_CONTACT_NAMES + 10; ++i) {
        mMatrixCursor.addRow(new Object[] { i, "name" + i, i, now, 1 });
    }
    mFakeContactsContentProvider.addQueryResult(Contacts.CONTENT_URI, mMatrixCursor);

    final ArrayList<String> validNames = mManager.getValidNames(Contacts.CONTENT_URI);
    assertEquals(ContactsManager.MAX_CONTACT_NAMES, validNames.size());
    for (int i = 0; i < 10; ++i) {
        assertFalse(validNames.contains("name" + i));
    }
    for (int i = 10; i < ContactsManager.MAX_CONTACT_NAMES + 10; ++i) {
        assertTrue(validNames.contains("name" + i));
    }
}
 
Example #26
Source File: ContactsBinaryDictionary.java    From Indic-Keyboard with Apache License 2.0 6 votes vote down vote up
/**
 * Loads data within content providers to the dictionary.
 */
private void loadDictionaryForUriLocked(final Uri uri) {
    if (!PermissionsUtil.checkAllPermissionsGranted(
            mContext, Manifest.permission.READ_CONTACTS)) {
        Log.i(TAG, "No permission to read contacts. Not loading the Dictionary.");
    }

    final ArrayList<String> validNames = mContactsManager.getValidNames(uri);
    for (final String name : validNames) {
        addNameLocked(name);
    }
    if (uri.equals(Contacts.CONTENT_URI)) {
        // Since we were able to add content successfully, update the local
        // state of the manager.
        mContactsManager.updateLocalState(validNames);
    }
}
 
Example #27
Source File: InsertContactsCommand.java    From mobilecloud-15 with Apache License 2.0 6 votes vote down vote up
/**
 * Synchronously insert a contact with the designated @name into
 * the ContactsContentProvider.  This code is explained at
 * http://developer.android.com/reference/android/provider/ContactsContract.RawContacts.html.
 */
private void addContact(String name,
                        List<ContentProviderOperation> cpops) {
    final int position = cpops.size();

    // First part of operation.
    cpops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
              .withValue(RawContacts.ACCOUNT_TYPE,
                         mOps.getAccountType())
              .withValue(RawContacts.ACCOUNT_NAME,
                         mOps.getAccountName())
              .withValue(Contacts.STARRED,
                         1)
              .build());

    // Second part of operation.
    cpops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
              .withValueBackReference(Data.RAW_CONTACT_ID,
                                      position)
              .withValue(Data.MIMETYPE,
                         StructuredName.CONTENT_ITEM_TYPE)
              .withValue(StructuredName.DISPLAY_NAME,
                         name)
              .build());
}
 
Example #28
Source File: ContactDetailsActivity.java    From Pix-Art-Messenger with GNU General Public License v3.0 6 votes vote down vote up
private void editContact() {
    Uri systemAccount = contact.getSystemAccount();
    if (systemAccount == null) {
        quickEdit(contact.getServerName(), R.string.contact_name, value -> {
            contact.setServerName(value);
            ContactDetailsActivity.this.xmppConnectionService.pushContactToServer(contact);
            populateView();
            return null;
        }, true);
    } else {
        Intent intent = new Intent(Intent.ACTION_EDIT);
        intent.setDataAndType(systemAccount, Contacts.CONTENT_ITEM_TYPE);
        intent.putExtra("finishActivityOnSaveCompleted", true);
        try {
            startActivity(intent);
            overridePendingTransition(R.animator.fade_in, R.animator.fade_out);
        } catch (ActivityNotFoundException e) {
            ToastCompat.makeText(ContactDetailsActivity.this, R.string.no_application_found_to_view_contact, Toast.LENGTH_SHORT).show();
        }
    }
}
 
Example #29
Source File: ContactAccessor.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
public String getNameFromContact(Context context, Uri uri) {
  Cursor cursor = null;

  try {
    cursor = context.getContentResolver().query(uri, new String[] {Contacts.DISPLAY_NAME},
                                                null, null, null);

    if (cursor != null && cursor.moveToFirst())
      return cursor.getString(0);

  } finally {
    if (cursor != null)
      cursor.close();
  }

  return null;
}
 
Example #30
Source File: InsertContactsCommand.java    From mobilecloud-15 with Apache License 2.0 6 votes vote down vote up
/**
 * Synchronously insert a contact with the designated @name into
 * the ContactsContentProvider.  This code is explained at
 * http://developer.android.com/reference/android/provider/ContactsContract.RawContacts.html.
 */
private void addContact(String name,
                        List<ContentProviderOperation> cpops) {
    final int position = cpops.size();

    // First part of operation.
    cpops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
              .withValue(RawContacts.ACCOUNT_TYPE,
                         mOps.getAccountType())
              .withValue(RawContacts.ACCOUNT_NAME,
                         mOps.getAccountName())
              .withValue(Contacts.STARRED,
                         1)
              .build());

    // Second part of operation.
    cpops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
              .withValueBackReference(Data.RAW_CONTACT_ID,
                                      position)
              .withValue(Data.MIMETYPE,
                         StructuredName.CONTENT_ITEM_TYPE)
              .withValue(StructuredName.DISPLAY_NAME,
                         name)
              .build());
}