Java Code Examples for android.provider.ContactsContract

The following are top voted examples for showing how to use android.provider.ContactsContract. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: PeSanKita-android   File: ConversationListActivity.java   Source Code and License 7 votes vote down vote up
private void initializeContactUpdatesReceiver() {
  observer = new ContentObserver(null) {
    @Override
    public void onChange(boolean selfChange) {
      super.onChange(selfChange);
      Log.w(TAG, "Detected android contact data changed, refreshing cache");
      RecipientFactory.clearCache(ConversationListActivity.this);
      ConversationListActivity.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
          chatsFragment.getListAdapter().notifyDataSetChanged();
        }
      });
    }
  };

  getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI,
          true, observer);
}
 
Example 2
Project: Cable-Android   File: ContactIdentityManagerICS.java   Source Code and License 6 votes vote down vote up
@SuppressLint("NewApi")
@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 3
Project: androidbeginners-Lesson3   File: MainActivity.java   Source Code and License 6 votes vote down vote up
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {

    String[]  projectionFields = new String[]{
        ContactsContract.Contacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME,
            ContactsContract.Contacts.PHOTO_URI
    };


    CursorLoader cursorLoader = new CursorLoader(MainActivity.this,
            ContactsContract.Contacts.CONTENT_URI,
            projectionFields,
            null,
            null,
            null);

    return cursorLoader;
}
 
Example 4
Project: SOS-The-Healthcare-Companion   File: ContactPickerActivity.java   Source Code and License 6 votes vote down vote up
private void readContactDetails(Cursor cursor) {
    if (cursor != null && cursor.moveToFirst()) {
        cursor.moveToPrevious();
        while (cursor.moveToNext()) {
            String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.LOOKUP_KEY));
            ContactImpl contact = mContactsByLookupKey.get(lookupKey);

            if (contact != null) {
                readContactDetails(cursor, contact);
            }
        }
    }

    sortAndPostCopy(mContacts);
    joinContactsAndGroups(mContacts);
}
 
Example 5
Project: ShotsNewsApp   File: LoginActivity.java   Source Code and License 6 votes vote down vote up
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
    return new CursorLoader(this,
            // Retrieve data rows for the device user's 'profile' contact.
            Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
                    ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,

            // Select only email addresses.
            ContactsContract.Contacts.Data.MIMETYPE +
                    " = ?", new String[]{ContactsContract.CommonDataKinds.Email
            .CONTENT_ITEM_TYPE},

            // Show primary email addresses first. Note that there won't be
            // a primary email address if the user hasn't specified one.
            ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
 
Example 6
Project: Impala   File: Utils.java   Source Code and License 6 votes vote down vote up
public static List<String> getNameEmailDetails(ContentResolver resolver) {
    ArrayList<String> names = new ArrayList<>();
    Cursor cur = resolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor cur1 =
                resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
                    new String[] { id }, null);
            getEmailFromCursor(names, cur1);
            cur1.close();
        }
    }
    return names;
}
 
Example 7
Project: Cable-Android   File: WebRtcCallScreen.java   Source Code and License 6 votes vote down vote up
private void setPersonInfo(final @NonNull Recipient recipient) {
  this.recipient = recipient;
  this.recipient.addListener(this);

  final Context context = getContext();

  new AsyncTask<Void, Void, ContactPhoto>() {
    @Override
    protected ContactPhoto doInBackground(Void... params) {
      DisplayMetrics metrics       = new DisplayMetrics();
      WindowManager  windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
      Uri            contentUri    = ContactsContract.Contacts.lookupContact(context.getContentResolver(),
                                                                             recipient.getContactUri());
      windowManager.getDefaultDisplay().getMetrics(metrics);
      return ContactPhotoFactory.getContactPhoto(context, contentUri, null, metrics.widthPixels);
    }

    @Override
    protected void onPostExecute(final ContactPhoto contactPhoto) {
      WebRtcCallScreen.this.photo.setImageDrawable(contactPhoto.asCallCard(context));
    }
  }.execute();

  this.name.setText(recipient.getName());
  this.phoneNumber.setText(recipient.getNumber());
}
 
Example 8
Project: q-mail   File: Contacts.java   Source Code and License 6 votes vote down vote up
/**
 * Start the activity to add information to an existing contact or add a
 * new one.
 *
 * @param email An {@link Address} instance containing the email address
 *              of the entity you want to add to the contacts. Optionally
 *              the instance also contains the (display) name of that
 *              entity.
 */
public void createContact(final Address email) {
    final Uri contactUri = Uri.fromParts("mailto", email.getAddress(), null);

    final Intent contactIntent = new Intent(ContactsContract.Intents.SHOW_OR_CREATE_CONTACT);
    contactIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    contactIntent.setData(contactUri);

    // Pass along full E-mail string for possible create dialog
    contactIntent.putExtra(ContactsContract.Intents.EXTRA_CREATE_DESCRIPTION,
            email.toString());

    // Only provide personal name hint if we have one
    final String senderPersonal = email.getPersonal();
    if (senderPersonal != null) {
        contactIntent.putExtra(ContactsContract.Intents.Insert.NAME, senderPersonal);
    }

    mContext.startActivity(contactIntent);
}
 
Example 9
Project: card-reader   File: ContactsActivity.java   Source Code and License 6 votes vote down vote up
/**
 * Starts the contacts intent and requests permission to write to contacts if permission doesn't exist
 */
public void startContactsActivityIntent(){
    String[] permissions = {"android.permission.WRITE_CONTACTS"};
    Intent intent = new Intent(ContactsContract.Intents.Insert.ACTION);
    intent.setType(ContactsContract.RawContacts.CONTENT_TYPE);
    if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS) != PackageManager
            .PERMISSION_GRANTED){
        ActivityCompat.requestPermissions(this, permissions, CONTACTS_PERMISSION);
    }
    else {
        if (intent.resolveActivity(getPackageManager()) != null) {
            intent.putExtra(ContactsContract.Intents.Insert.NAME, name);
            intent.putExtra(ContactsContract.Intents.Insert.EMAIL, email);
            intent.putExtra(ContactsContract.Intents.Insert.PHONE, phone);
            startActivity(intent);
        }
    }
}
 
Example 10
Project: GitHub   File: ContactsPhotoRequestHandler.java   Source Code and License 6 votes vote down vote up
private InputStream getInputStream(Request data) throws IOException {
  ContentResolver contentResolver = context.getContentResolver();
  Uri uri = data.uri;
  switch (matcher.match(uri)) {
    case ID_LOOKUP:
      uri = ContactsContract.Contacts.lookupContact(contentResolver, uri);
      if (uri == null) {
        return null;
      }
      // Resolved the uri to a contact uri, intentionally fall through to process the resolved uri
    case ID_CONTACT:
      return openContactPhotoInputStream(contentResolver, uri, true);
    case ID_THUMBNAIL:
    case ID_DISPLAY_PHOTO:
      return contentResolver.openInputStream(uri);
    default:
      throw new IllegalStateException("Invalid uri: " + uri);
  }
}
 
Example 11
Project: Goalie_Android   File: FriendsActivity.java   Source Code and License 6 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    switch (id) {
        case android.R.id.home:
            finish();
            return true;
        case R.id.action_invite_friends:
            Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
            startActivityForResult(intent, Constants.REQUEST_PERMISSIONS_CONTACT);
            return true;
        case R.id.action_add_friends:
            AddContactDialog addContactDialog = new AddContactDialog();
            addContactDialog.setOnAdded(this);
            addContactDialog.show(getSupportFragmentManager(), "AddContactDialog");
            return true;
    }

    return super.onOptionsItemSelected(item);
}
 
Example 12
Project: android-contact-extractor   File: BaseContactQueryCB.java   Source Code and License 6 votes vote down vote up
@Override
public CName getName() {

    CName cName = new CName();
    String familyName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
    String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
    String givenName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
    String photoUri = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.PHOTO_URI));


    cName.setFamilyName(familyName);
    cName.setDisplayName(displayName);
    cName.setGivenName(givenName);
    cName.setPhotoUri(photoUri);

    return cName;
}
 
Example 13
Project: dapay   File: Login_BT_Activity.java   Source Code and License 6 votes vote down vote up
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
    return new CursorLoader(this,
            // Retrieve data rows for the device user's 'profile' contact.
            Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
                    ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,

            // Select only email addresses.
            ContactsContract.Contacts.Data.MIMETYPE +
                    " = ?", new String[]{ContactsContract.CommonDataKinds.Email
            .CONTENT_ITEM_TYPE},

            // Show primary email addresses first. Note that there won't be
            // a primary email address if the user hasn't specified one.
            ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
 
Example 14
Project: NewsApp   File: LoginActivity.java   Source Code and License 6 votes vote down vote up
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
    return new CursorLoader(this,
            // Retrieve data rows for the device user's 'profile' contact.
            Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
                    ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,

            // Select only email addresses.
            ContactsContract.Contacts.Data.MIMETYPE +
                    " = ?", new String[]{ContactsContract.CommonDataKinds.Email
            .CONTENT_ITEM_TYPE},

            // Show primary email addresses first. Note that there won't be
            // a primary email address if the user hasn't specified one.
            ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
 
Example 15
Project: AndroidContacts   File: ContactsGetter.java   Source Code and License 6 votes vote down vote up
private SparseArray<Group> getGroupsMap() {
    SparseArray<Group> idGroupMap = new SparseArray<>();
    Cursor groupCursor = mResolver.query(
        ContactsContract.Groups.CONTENT_URI,
        new String[]{
            ContactsContract.Groups._ID,
            ContactsContract.Groups.TITLE
        }, null, null, null
    );
    if (groupCursor != null) {
        while (groupCursor.moveToNext()) {
            int id = groupCursor.getInt(groupCursor.getColumnIndex(ContactsContract.Groups._ID));
            String title = groupCursor.getString(groupCursor.getColumnIndex(ContactsContract.Groups.TITLE));
            idGroupMap.put(id, new Group()
                .setGroupId(id)
                .setGroupTitle(title));
        }
        groupCursor.close();
    }
    return idGroupMap;
}
 
Example 16
Project: custode   File: ContactsPickerActivity.java   Source Code and License 6 votes vote down vote up
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    contactsAdapter.clear();

    Set<String> favoriteContacts = CustodeUtils.getFavoriteContacts(this);
    LinkedList<ContactsAdapter.ContactItem> tempArray = new LinkedList<>();
    int favoriteLimit = 0; // usato per ordinare i contatti preferiti in cima alla lista

    int nameColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
    int numberColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

    while (cursor.moveToNext()) {
        String name = cursor.getString(nameColumnIndex);
        String number = cursor.getString(numberColumnIndex);

        boolean favorite = favoriteContacts.remove(number);
        if (favorite)
            tempArray.add(favoriteLimit++, new ContactsAdapter.ContactItem(name, number, true));
        else
            tempArray.addLast(new ContactsAdapter.ContactItem(name, number, false));
    }

    if (favoriteContacts.size() > 0) // => favoriteContacts contiene numeri che non sono più presenti in rubrica
        for (String favoriteContact : favoriteContacts)
            tempArray.addFirst(new ContactsAdapter.ContactItem("", favoriteContact, true));

    contactsAdapter.addAll(tempArray);
}
 
Example 17
Project: Shared-Route   File: LoginActivity.java   Source Code and License 6 votes vote down vote up
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
    return new CursorLoader(this,
            // Retrieve data rows for the device user's 'profile' contact.
            Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
                    ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,

            // Select only email addresses.
            ContactsContract.Contacts.Data.MIMETYPE +
                    " = ?", new String[]{ContactsContract.CommonDataKinds.Email
            .CONTENT_ITEM_TYPE},

            // Show primary email addresses first. Note that there won't be
            // a primary email address if the user hasn't specified one.
            ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
 
Example 18
Project: PeSanKita-android   File: ContactSelectionListAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onBindItemViewHolder(ViewHolder viewHolder, @NonNull Cursor cursor) {
  long   id          = cursor.getLong(cursor.getColumnIndexOrThrow(ContactsDatabase.ID_COLUMN));
  int    contactType = cursor.getInt(cursor.getColumnIndexOrThrow(ContactsDatabase.CONTACT_TYPE_COLUMN));
  String name        = cursor.getString(cursor.getColumnIndexOrThrow(ContactsDatabase.NAME_COLUMN));
  String number      = cursor.getString(cursor.getColumnIndexOrThrow(ContactsDatabase.NUMBER_COLUMN));
  int    numberType  = cursor.getInt(cursor.getColumnIndexOrThrow(ContactsDatabase.NUMBER_TYPE_COLUMN));
  String label       = cursor.getString(cursor.getColumnIndexOrThrow(ContactsDatabase.LABEL_COLUMN));
  String labelText   = ContactsContract.CommonDataKinds.Phone.getTypeLabel(getContext().getResources(),
                                                                           numberType, label).toString();

  int color = (contactType == ContactsDatabase.PUSH_TYPE) ? drawables.getColor(0, 0xa0000000) :
              drawables.getColor(1, 0xff000000);

  boolean preSelected = numbers != null && numbers.contains(number);

  viewHolder.getView().unbind();
  viewHolder.getView().set(id, contactType, name, number, labelText, color, multiSelect);
  viewHolder.getView().setChecked(preSelected || selectedContacts.containsKey(id));
  viewHolder.getView().setEnabled(!preSelected);
}
 
Example 19
Project: amap   File: AddressServiceImpl.java   Source Code and License 6 votes vote down vote up
private static void addContactToGroup(ContentResolver mResolver, int contactId, int groupId)
{
    // judge whether the contact has been in the group
    boolean b1 = ifExistContactInGroup(mResolver, contactId, groupId);
    if (b1)
    {
        // the contact has been in the group
        return;
    }
    else
    {
        ContentValues values = new ContentValues();
        values.put(ContactsContract.CommonDataKinds.GroupMembership.RAW_CONTACT_ID, contactId);
        values.put(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID, groupId);
        values.put(ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE,
            ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE);
        mResolver.insert(ContactsContract.Data.CONTENT_URI, values);
    }
}
 
Example 20
Project: PeSanKita-android   File: AvatarImageView.java   Source Code and License 6 votes vote down vote up
private void setAvatarClickHandler(final Recipients recipients, boolean quickContactEnabled) {
  if (!recipients.isGroupRecipient() && quickContactEnabled) {
    setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Recipient recipient = recipients.getPrimaryRecipient();

        if (recipient != null && recipient.getContactUri() != null) {
          ContactsContract.QuickContact.showQuickContact(getContext(), AvatarImageView.this, recipient.getContactUri(), ContactsContract.QuickContact.MODE_LARGE, null);
        } else if (recipient != null) {
          final Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
          intent.putExtra(ContactsContract.Intents.Insert.PHONE, recipient.getNumber());
          intent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
          getContext().startActivity(intent);
        }
      }
    });
  } else {
    setOnClickListener(null);
  }
}
 
Example 21
Project: Raffler-Android   File: RegisterUserActivity.java   Source Code and License 6 votes vote down vote up
private void loadUserInfoFromPhone(){
    User user = AppManager.getSession();
    if (user != null) {
        etName.setText(user.getName());
        Util.setProfileImage(user.getPhoto(), imgProfile);
    } else {
        if (checkPermissions()) {
            String[] projection = new String[] {
                    Phone.DISPLAY_NAME,
                    Phone.HAS_PHONE_NUMBER,
                    Phone.NUMBER,
                    Phone.CONTACT_ID};

            Cursor cursor = getApplication().getContentResolver().query(ContactsContract.Profile.CONTENT_URI, null, null, null, null);
            if (cursor.moveToFirst()){
                etName.setText(cursor.getString(cursor.getColumnIndex("display_name")));
            }
            cursor.close();
        }
    }
}
 
Example 22
Project: alerta-fraude   File: ContactAccessorSdk5.java   Source Code and License 6 votes vote down vote up
@Override
/**
 * This method will remove a Contact from the database based on ID.
 * @param id the unique ID of the contact to remove
 */
public boolean remove(String id) {
    int result = 0;
    Cursor cursor = mApp.getActivity().getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
            null,
            ContactsContract.Contacts._ID + " = ?",
            new String[] { id }, null);

    if (cursor.getCount() == 1) {
        cursor.moveToFirst();
        String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
        Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
        result = mApp.getActivity().getContentResolver().delete(uri, null, null);
    } else {
        LOG.d(LOG_TAG, "Could not find contact with ID");
    }

    return (result > 0) ? true : false;
}
 
Example 23
Project: permissions4m   File: PermissionsChecker.java   Source Code and License 6 votes vote down vote up
/**
 * read contacts, {@link android.Manifest.permission#READ_CONTACTS}
 *
 * @param activity
 * @return true if success
 * @throws Exception
 */
private static boolean checkReadContacts(Activity activity) throws Exception {
    Cursor cursor = activity.getContentResolver().query(ContactsContract.CommonDataKinds.Phone
            .CONTENT_URI, null, null, null, null);
    if (cursor != null) {
        if (ManufacturerSupportUtil.isForceManufacturer()) {
            if (isNumberIndexInfoIsNull(cursor, cursor.getColumnIndex(ContactsContract.CommonDataKinds
                    .Phone.NUMBER))) {
                cursor.close();
                return false;
            }
        }
        cursor.close();
        return true;
    } else {
        return false;
    }
}
 
Example 24
Project: contacts-search-android   File: ContactFetcher.java   Source Code and License 5 votes vote down vote up
public void matchContactEmails(Map<String, Contact> contactsMap) {
    // Get email
    final String[] emailProjection = new String[]{
            Email.DATA,
            Email.TYPE,
            Email.CONTACT_ID,
    };

    Cursor email = new CursorLoader(context,
            Email.CONTENT_URI,
            emailProjection,
            null,
            null,
            null).loadInBackground();

    if (email.moveToFirst()) {
        final int contactEmailColumnIndex = email.getColumnIndex(Email.DATA);
        final int contactTypeColumnIndex = email.getColumnIndex(Email.TYPE);
        final int contactIdColumnsIndex = email.getColumnIndex(Email.CONTACT_ID);

        while (!email.isAfterLast()) {
            final String address = email.getString(contactEmailColumnIndex);
            final String contactId = email.getString(contactIdColumnsIndex);
            final int type = email.getInt(contactTypeColumnIndex);
            String customLabel = "Custom";
            Contact contact = contactsMap.get(contactId);
            if (contact == null) {
                continue;
            }
            CharSequence emailType = ContactsContract.CommonDataKinds.Email.getTypeLabel(context.getResources(), type, customLabel);
            contact.addEmail(address, emailType.toString());
            email.moveToNext();
        }
    }

    email.close();
}
 
Example 25
Project: Sendroid   File: ImageDecorder.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
protected InputStream getContactPhotoStream(Uri uri) {
    ContentResolver res = context.getContentResolver();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        return ContactsContract.Contacts.openContactPhotoInputStream(res, uri, true);
    } else {
        return ContactsContract.Contacts.openContactPhotoInputStream(res, uri);
    }
}
 
Example 26
Project: ContentPal   File: RawContactsProjection.java   Source Code and License 5 votes vote down vote up
public RawContactsProjection()
{
    // TODO: it's probably better to compose this from smaller projections with just a few columns
    super(new MultiProjection<ContactsContract.RawContacts>(
            ContactsContract.RawContacts._ID,
            ContactsContract.RawContacts.CONTACT_ID,
            ContactsContract.RawContacts.AGGREGATION_MODE,
            ContactsContract.RawContacts.DELETED,
            // the following column doesn't seem to work on Android 7.1
            //ContactsContract.RawContacts.RAW_CONTACT_IS_READ_ONLY,

            // values from ContactNameColumns
            ContactsContract.RawContacts.DISPLAY_NAME_SOURCE,
            ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY,
            ContactsContract.RawContacts.DISPLAY_NAME_ALTERNATIVE,
            ContactsContract.RawContacts.PHONETIC_NAME_STYLE,
            ContactsContract.RawContacts.PHONETIC_NAME,
            ContactsContract.RawContacts.SORT_KEY_PRIMARY,
            ContactsContract.RawContacts.SORT_KEY_ALTERNATIVE,

            // values from SyncColumns
            ContactsContract.RawContacts.ACCOUNT_NAME,
            ContactsContract.RawContacts.ACCOUNT_TYPE,
            ContactsContract.RawContacts.DIRTY,
            ContactsContract.RawContacts.SOURCE_ID,
            ContactsContract.RawContacts.VERSION));
}
 
Example 27
Project: RLibrary   File: ContactsPickerHelper.java   Source Code and License 5 votes vote down vote up
/**
     * 同步返回联系人列表
     */
    public static List<ContactsInfo> getContactsList(Context context) {

        //检查权限
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                return  new ArrayList<>();
            }
        }

        final ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, new String[]{"_id"}, null, null, null);
        List<ContactsInfo> contactsInfos = new ArrayList<>();

        if (cursor != null) {
            //枚举所有联系人的id
            if (cursor.getCount() > 0) {
                L.w("联系人总数量:" + cursor.getCount()); //就是联系人的总数
                int count = 0;
                if (cursor.moveToFirst()) {
                    do {
                        int contactIdIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);//获取 id 所在列的索引
                        String contactId = cursor.getString(contactIdIndex);//联系人id

                        final List<String> phones = getData1(contentResolver, contactId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                        if (phones.isEmpty()) {
                            continue;
                        } else {
                            String name;
                            final List<String> names = getData1(contentResolver, contactId, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
                            if (names.isEmpty()) {
                                name = phones.get(0);
                            } else {
                                name = names.get(0);
                            }

                            //相同联系人的不同手机号码视为不同的联系人
                            for (String phone : phones) {
                                // 去除非手机号
                                if (!RegexUtils.isMobileExact(StringUtil.removeBlanks(phone))) {
                                    continue;
                                }
                                ContactsInfo io = new ContactsInfo();
                                io.contactId = contactId;
                                io.name = name;
                                io.phone = StringUtil.removeBlanks(phone);
                                io.letter = String.valueOf(Pinyin.toPinyin(name.charAt(0)).toUpperCase().charAt(0));
                                contactsInfos.add(io);
                            }
                        }

//                    L.e("-------------------------" + count + "----------------------");
//                    L.w("联系人ID:" + contactId);
//                    final String name = getData1(contentResolver, contactId, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
//                    L.w("联系人名称:" + Pinyin.toPinyin(name.charAt(0)).toUpperCase().charAt(0) + " " + name);
//                    L.w("联系人电话:" + getData1(contentResolver, contactId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE));
//                    logData(contentResolver, contactId);
//                    count++;
                    } while (cursor.moveToNext());
                }
            }
            cursor.close();
        }
        return contactsInfos;
    }
 
Example 28
Project: ContentPal   File: OfficeLocationData.java   Source Code and License 5 votes vote down vote up
@NonNull
@Override
public ContentProviderOperation.Builder updatedBuilder(TransactionContext transactionContext, @NonNull ContentProviderOperation.Builder builder)
{
    return mDelegate.updatedBuilder(transactionContext, builder)
            .withValue(ContactsContract.CommonDataKinds.Organization.OFFICE_LOCATION, mOfficeLocation == null ? null : mOfficeLocation.toString());
}
 
Example 29
Project: android-contact-extractor   File: BaseContactQueryCB.java   Source Code and License 5 votes vote down vote up
@Override
public CEvents getEvents() {

    CEvents cEvents = new CEvents();

    String startData = cursor.getString(
            cursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));

    int type = cursor.getInt(
            cursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.TYPE));

    switch (type) {
        case ContactsContract.CommonDataKinds.Event.TYPE_ANNIVERSARY:
            cEvents.setAnniversay(startData);
            break;

        case ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY:
            cEvents.setBirthDay(startData);
            break;
        default:
            break;
    }

    cEvents.setDisplayName(cursor.getString(
            cursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.DISPLAY_NAME)));

    cEvents.setPhotoUri(cursor.getString(
            cursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.PHOTO_URI)));

    return cEvents;
}
 
Example 30
Project: GitHub   File: MyCursorLoader.java   Source Code and License 5 votes vote down vote up
/**
 * 查询数据等操作放在这里执行
 */
@Override
protected Cursor onLoadInBackground() {
    Cursor cursor = mContext.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
            mContactProjection, null,null, null);
    return cursor;
}
 
Example 31
Project: ContentPal   File: Prefixed.java   Source Code and License 5 votes vote down vote up
@NonNull
@Override
public ContentProviderOperation.Builder updatedBuilder(TransactionContext transactionContext, @NonNull ContentProviderOperation.Builder builder)
{
    return mDelegate.updatedBuilder(transactionContext, builder)
            .withValue(ContactsContract.CommonDataKinds.StructuredName.PREFIX, mPrefix == null ? null : mPrefix.toString());
}
 
Example 32
Project: XPermission   File: PermissionsChecker.java   Source Code and License 5 votes vote down vote up
/**
 * write and delete contacts info, {@link Manifest.permission#WRITE_CONTACTS}
 * and we should get read contacts permission first.
 *
 * @param activity
 * @return true if success
 * @throws Exception
 */
private static boolean checkWriteContacts(Context activity) throws Exception {
    if (checkReadContacts(activity)) {
        // write some info
        ContentValues values = new ContentValues();
        ContentResolver contentResolver = activity.getContentResolver();
        Uri rawContactUri = contentResolver.insert(ContactsContract.RawContacts
                .CONTENT_URI, values);
        long rawContactId = ContentUris.parseId(rawContactUri);
        values.put(ContactsContract.Contacts.Data.MIMETYPE, ContactsContract.CommonDataKinds
                .StructuredName.CONTENT_ITEM_TYPE);
        values.put(ContactsContract.Contacts.Data.RAW_CONTACT_ID, rawContactId);
        values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, TAG);
        values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, TAG_NUMBER);
        contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

        // delete info
        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        ContentResolver resolver = activity.getContentResolver();
        Cursor cursor = resolver.query(uri, new String[]{ContactsContract.Contacts.Data._ID},
                "display_name=?", new String[]{TAG}, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int id = cursor.getInt(0);
                resolver.delete(uri, "display_name=?", new String[]{TAG});
                uri = Uri.parse("content://com.android.contacts/data");
                resolver.delete(uri, "raw_contact_id=?", new String[]{id + ""});
            }
            cursor.close();
        }
        return true;
    } else {
        return false;
    }
}
 
Example 33
Project: alerta-fraude   File: ContactAccessorSdk5.java   Source Code and License 5 votes vote down vote up
/**
 * Add a phone to a list of database actions to be performed
 *
 * @param ops the list of database actions
 * @param phone the item to be inserted
 */
private void insertPhone(ArrayList<ContentProviderOperation> ops,
        JSONObject phone) {
    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
            .withValue(ContactsContract.Data.MIMETYPE, CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
            .withValue(CommonDataKinds.Phone.NUMBER, getJsonString(phone, "value"))
            .withValue(CommonDataKinds.Phone.TYPE, getPhoneType(getJsonString(phone, "type")))
            .withValue(Phone.LABEL, getJsonString(phone, "type"))
            .build());
}
 
Example 34
Project: UnifiedContactPicker   File: ContactPickerFragment.java   Source Code and License 5 votes vote down vote up
/**
 * When the system finishes retrieving the Cursor through the CursorLoader,
 * a call to the onLoadFinished() method takes place.
 **/
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    if(cursor.moveToFirst()){
        do{
            String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            String communication = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            Contact newContact = new Contact(displayName);

            Contact suggestion = new Contact(displayName);
            suggestion.addCommunication(communication);
            mSuggestions.add(suggestion);

            if(!mContacts.contains(newContact)){
                newContact.addCommunication(communication);
                mContacts.add(newContact);
            }else{
                Contact existingContact = mContacts.get(mContacts.indexOf(newContact));
                existingContact.addCommunication(communication);
            }

        }while(cursor.moveToNext());
    }
    if(mContactAdapter != null) {
        mContactAdapter.notifyDataSetChanged();
    }

    setRecyclerView();
    AutoCompleteAdapter adapter = new AutoCompleteAdapter(getContext(),R.layout.cp_suggestion_row, mSuggestions);
    this.mNachoTextView.setAdapter(adapter);
}
 
Example 35
Project: Linphone4Android   File: LinphoneContact.java   Source Code and License 5 votes vote down vote up
public void setOrganization(String org) {
	if (isAndroidContact()) {
		if (androidRawId != null) {
			String select = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "='" + CommonDataKinds.Organization.CONTENT_ITEM_TYPE + "'";
			String[] args = new String[]{ getAndroidId() };

			if (organization != null) {
				changesToCommit.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
					.withSelection(select, args)
					.withValue(ContactsContract.Data.MIMETYPE, CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
					.withValue(CommonDataKinds.Organization.COMPANY, org)
					.build());
			} else {
				changesToCommit.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
					.withValue(ContactsContract.Data.RAW_CONTACT_ID, androidRawId)
					.withValue(ContactsContract.Data.MIMETYPE, CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
					.withValue(CommonDataKinds.Organization.COMPANY, org)
					.build());
			}
		} else {
			changesToCommit.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
		        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
		        .withValue(ContactsContract.Data.MIMETYPE, CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
		        .withValue(CommonDataKinds.Organization.COMPANY, org)
		        .build());
		}
	}

	organization = org;
}
 
Example 36
Project: SOS-The-Healthcare-Companion   File: ContactPickerActivity.java   Source Code and License 5 votes vote down vote up
private void readContacts(Cursor cursor) {
    mContacts.clear();
    mContactsByLookupKey.clear();
    mNrOfSelectedContacts = 0;

    int count = 0;
    if (cursor.moveToFirst()) {
        cursor.moveToPrevious();
        while (cursor.moveToNext()) {
            ContactImpl contact = ContactImpl.fromCursor(cursor);
            mContacts.add(contact);

            // LOOKUP_KEY is the one we use to retrieve the contact when the contact details are loaded
            String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
            mContactsByLookupKey.put(lookupKey, contact);

            boolean isChecked = mSelectedContactIds.contains(contact.getId());
            contact.setChecked(isChecked, true);
            mNrOfSelectedContacts += isChecked ? 1 : 0;

            contact.addOnContactCheckedListener(mContactListener);

            // update the ui once some contacts have loaded
            if (++count >= BATCH_SIZE) {
                sortAndPostCopy(mContacts);
                count = 0;
            }
        }
    }

    if (count > 0) {
        sortAndPostCopy(mContacts);
    }

    updateTitle();
}
 
Example 37
Project: chapp-messenger   File: Contacts.java   Source Code and License 5 votes vote down vote up
public Map<String,String> ReadKontakte(ContentResolver cr) {
    Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    Map<String,String> alContacts = new HashMap<String,String>();
    if(cursor.moveToFirst())
    {
        do
        {
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));

            if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
            {
                Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{ id }, null);
                while (pCur.moveToNext())
                {
                    String contactNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    //String contactNumber = "11111111";
                    String name = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    //Invalid key: Dr. Jakob Ott. Keys must not contain '/', '.', '#', '$', '[', or ']'
                    name = name.replace(".", "");
                    name = name.replace("/", "");
                    name = name.replace("#", "");
                    name = name.replace("$", "");
                    name = name.replace("[", "");
                    name = name.replace("]", "");
                    contactNumber = contactNumber.replace(" ", "");
                    contactNumber = standardisiereAUT(contactNumber);       // fügt +43 an alles
                    alContacts.put(name, contactNumber);
                    break;
                }
                pCur.close();
            }
        } while (cursor.moveToNext()) ;
    }
    return alContacts;
}
 
Example 38
Project: FinalProject   File: ContactsHelper.java   Source Code and License 5 votes vote down vote up
public static ArrayList<String> readContacts(ContentResolver contentResolver) {
  long startTime;
  long endTime;
  ArrayList<String> contactsList = new ArrayList<>();
  startTime = System.currentTimeMillis();
  Timber.d(String.valueOf("CONTACTS-SYNC : START- TIME" + startTime));

  Cursor phones =
      contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null,
          null);
  if (phones != null) {
    while (phones.moveToNext()) {
      String phoneNumber =
          phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
      if (!contactsList.contains(RegexHandler.removeSpecialCharacters(phoneNumber))) {
        contactsList.add(RegexHandler.removeSpecialCharacters(phoneNumber));
      }
      Timber.d(String.valueOf(phoneNumber + " size: " + contactsList.size()));
    }
    phones.close();
    endTime = System.currentTimeMillis();
    Timber.d(String.valueOf("CONTACTS-SYNC : END- TIME : " + endTime));
    Timber.d(String.valueOf("CONTACTS-SYNC : START- TIME : " + startTime));
    Timber.d(String.valueOf("CONTACTS-SYNC : ELAPSED- TIME : " + (endTime - startTime) / 6000));
    return contactsList;
  }
  return contactsList;
}
 
Example 39
Project: ContentPal   File: Local.java   Source Code and License 5 votes vote down vote up
@NonNull
@Override
public Cursor rows(@NonNull UriParams uriParams, @NonNull Projection<ContactsContract.RawContacts> projection, @NonNull Predicate predicate, @NonNull Optional<String> sorting) throws RemoteException
{
    return mDelegate.rows(uriParams,
            projection,
            new AllOf(predicate, new IsNull(ContactsContract.RawContacts.ACCOUNT_NAME), new IsNull(ContactsContract.RawContacts.ACCOUNT_TYPE)), sorting);
}
 
Example 40
Project: Linphone4Android   File: LinphoneContact.java   Source Code and License 5 votes vote down vote up
private void createLinphoneContactTag() {
	ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();

	batch.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
		.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, ContactsManager.getInstance().getString(R.string.sync_account_type))
		.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, ContactsManager.getInstance().getString(R.string.sync_account_name))
		.withValue(ContactsContract.RawContacts.AGGREGATION_MODE, ContactsContract.RawContacts.AGGREGATION_MODE_DEFAULT)
		.build());

	batch.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
		.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
		.withValue(ContactsContract.Data.MIMETYPE, CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
		.withValue(CommonDataKinds.StructuredName.DISPLAY_NAME, getFullName())
		.build());

	batch.add(ContentProviderOperation.newUpdate(ContactsContract.AggregationExceptions.CONTENT_URI)
		.withValue(ContactsContract.AggregationExceptions.TYPE, ContactsContract.AggregationExceptions.TYPE_KEEP_TOGETHER)
		.withValue(ContactsContract.AggregationExceptions.RAW_CONTACT_ID1, androidRawId)
		.withValueBackReference(ContactsContract.AggregationExceptions.RAW_CONTACT_ID2, 0)
		.build());

	if (changesToCommit2.size() > 0) {
		for(ContentProviderOperation cpo : changesToCommit2) {
			batch.add(cpo);
		}
	}

	try {
		ContactsManager.getInstance().getContentResolver().applyBatch(ContactsContract.AUTHORITY, batch);
		androidTagId = findLinphoneRawContactId();
	} catch (Exception e) {
		Log.e(e);
	}
}