Below is the code I used to get all contacts from phone.
public static ArrayList<Recipient> getAllRecipient(Context context) {
ArrayList<Recipient> contacts = new ArrayList<>();
Cursor cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cursor != null) {
try {
final int displayNameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
final int numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
final int typeIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
final int uriIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI);
String displayName, number, uri;
while (cursor.moveToNext()) {
int type = cursor.getInt(typeIndex);
if (type == ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE) {
displayName = cursor.getString(displayNameIndex);
number = cursor.getString(numberIndex);
number = number.replaceAll("[^0-9+]+", "");//remove all special character and space, just keep digit number and "+"
uri = cursor.getString(uriIndex);
Recipient recipient = new Recipient(displayName, number, uri);
contacts.add(recipient);
}
}
} catch (Exception e) {
LogUtil.debug("can't get recipient: " + e.getMessage());
} finally {
cursor.close();
}
}
cursor.close();
return contacts;
}
I got feedback from many users , they can not get full contacts in their phones, show almost contacts but missed some contacts.
Is there any problem with above code ? Thanks.
Use this code
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
Phone.CONTENT_URI includes all Phone entries of the device. If a contact does not have some phone you are not going to get any information about it.
If contacts is what you are after, you should query the ContactsContract.Contacts.CONTENT_URI.
Keep in mind that contacts and phone are two separate things for Android. Not all contacts have phone numbers and you would have to query the numbers separately.
Related
I am trying to get all contact from my phone, including get all numbers from contacts with multiple numbers.
So i've build query that while not over run all over contacts, and build Contact user, and have inside query with id selection to get all numbers for each user. but since my inside query is including selection it takes a long time. any other idea?
private Cursor initPhoneCursor() {
try {
// get the contacts URI
final Uri phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
// get the name column's name depending on the Android Version
final String nameColumn = Contact.COLUMN_NAME_PHONE;
// declare columns object - init later depending on version
String selection = getQuerySelectionForCursor();
String[] columns = getColumnSelectionForCursor(nameColumn);
if (mApp != null) {
// return cursor from contentresolver
return mApp.getContentResolver().query(phoneUri, columns, selection, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
}
} catch (Exception e) {
// couldn't read phone cursor
CaughtExceptionHandler.reportException(e);
}
return null;
}
private void importContactsFromCursor(Cursor cursor, boolean isSimCard) {
mCurrentContactCursor = initPhoneCursor();
// check cursor is alive
if (cursor != null && !cursor.isClosed()) {
while (cursor.moveToNext() && shouldContinueImport()) {
// // as log as we have contacts, move through them
importContact(cursor, isSimCard);
mCurrentContact++;
}
// when done - close the cursor
cursor.close();
}
}
private void importContact(Cursor cursor, boolean simCard) {
// create Contact object
Contact row = new Contact(cursor, simCard);
// mContactsTimer.onContactCreated();
if (simCard) {
// if simCard, contact must have number
// validate number and create contact
row = validateAndCheckNumber(row, cursor);
}
else {
// if not sim card (phone cursor), a contact might have no numbers,
// single or multiple phone numberss
// let's check if this contact has any numbers
if (hasPhoneNumbers(cursor)) {
// get all of the contact's phone numbers
row = importAllNumbersForContact(row);
}
}
// check if this is valid
final boolean isValidForSaving = row != null && row.hasName() && row.hasNumbers();
if (isValidForSaving && !sStopRequested) {
mContactsToSave.add(row);
}
}
private Contact importAllNumbersForContact(Contact contact) {
// uri of contact phones
Uri contentUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
// contact_id = ?
String selection = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?";
String[] selectionArgs = {String.valueOf(contact.getOriginalId())};
// do the query
Cursor phoneCursor = mApp.getContentResolver().query(contentUri, null, selection, selectionArgs, null);
if (phoneCursor != null) {
// save numbers if we got anything
contact = loopThroughContactNumbers(contact, phoneCursor);
// close cursor when done
phoneCursor.close();
}
return contact;
}
Go with the following solution:
Map<String,Contact> contactsMap = new TreeMap<>();
contacts = new ArrayList<>();
Cursor phones = getBaseContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" ASC");
assert phones != null;
while (phones.moveToNext())
{
Contact contact = new Contact();
contact.setDisplayName(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
contact.setPhoneNumber(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
contact.setDisplayPicture(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI)));
contactsMap.put(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)),contact);
}
contacts.addAll(contactsMap.values());
phones.close();
Modify it for all numbers of a contact. You are good to go with.
I am trying to read contacts from device. I am getting the list of device contacts , but the problem is most of them are duplicates. But in my default contacts app those duplicates are not there. Right now it is returning around 1150 contacts from device out of that around 602 are duplicates (when I checked the result using log), but my default contacts App is not showing this duplicates. This is my code
private void readPhoneContacts(Context context) {
try {
Cursor cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
HashMap<String, Contact> mContactListItems = new HashMap<>();
if (cursor != null) {
while (cursor.moveToNext()) {
String key = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String image_uri = "";
String phoneNumber = "";
String name = "";
String emailId = null;
int image_urlCursorIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI);
if (!cursor.isNull(image_urlCursorIndex)) {
image_uri = cursor.getString(image_urlCursorIndex);
}
int phoneNumberCursorIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
if (!cursor.isNull(phoneNumberCursorIndex)) {
phoneNumber = cursor.getString(phoneNumberCursorIndex);
}
int nameCursorIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
if (!cursor.isNull(nameCursorIndex)) {
name = cursor.getString(nameCursorIndex);
}
emailId = cursor.getString(ContactsContract.CommonDataKinds.Email.TYPE_HOME);
Contact contact = new Contact();
contact.setName(name);
contact.setEmailId(emailId);
contact.setMobileNumber(phoneNumber);
contact.setId(key);
key = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
if (image_uri != null && !image_uri.isEmpty()) {
contact.setHasLocalContactImage(true);
contact.setDeviceContactImageUri(Uri.parse(image_uri));
}
mContactListItems.put(String.valueOf(key), contact);
}
cursor.close();
}
} catch (SQLiteException e) {
} catch (SecurityException e) {
} catch (Exception e) {
}
}
What I want to get is Id , Name , Phone number , Email Id of all contacts from device. Also it should list all types of phone and email (home , office etc). Is there any way to avoid duplicates and get these data? Thanks in advance.
I'm create an application to get all contacts from phone book of Android device. I synch my contacts list from Gmail to android device and I see all contacts in phone book. But when running application, cannot get any contacts from phone book.
Here is my code
MainActivity.java
public class MainActivity extends Activity {
private TextView outputText;
TextView txtViewContactsInfor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
outputText =(TextView)findViewById(R.id.textView2);
txtViewContactsInfor = (TextView) findViewById(R.id.txtViewContactsInfor);
Import_contacts_from_address_book();
}
private void Import_contacts_from_address_book() {
// TODO Auto-generated method stub
String phoneNumber = null;
String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PHONECONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String PHONECONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
Uri EMAILCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EMAILCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String EMAIL = ContactsContract.CommonDataKinds.Email.DATA;
StringBuffer output = new StringBuffer();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
System.out.println("---------------------->"+cursor.getCount());
if(cursor.getCount() >0){
int aa = cursor.getCount();
while(cursor.moveToNext()){
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if(hasPhoneNumber > 0 ){
output.append("\nFirst Name: "+name);
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(PHONECONTENT_URI, null, PHONECONTACT_ID + "=?", new String[]{contact_id}, null);
while(phoneCursor.moveToNext()){
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number: "+phoneNumber);
}
phoneCursor.close();
// Query and loop for every email of the contact
Cursor emailCurosr = contentResolver.query(EMAILCONTENT_URI, null, EMAILCONTACT_ID+"=?",new String[]{contact_id},null);
while(emailCurosr.moveToNext()){
email = emailCurosr.getString(emailCurosr.getColumnIndex(EMAIL));
output.append("\nEmail: "+email);
}
emailCurosr.close();
}
output.append("\n");
}
cursor.close();
}
outputText.setText(output.toString());
}
I debug in cursor.getCount and see "544 contact" was found. But
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER))); always zero.
I dont know why.
You might have a lot contacts without number, because contacts are stored in multiple columns.
I simplified and modified your code to count rows with and with out numbers and let it run on my phone:
private void readContacts() {
Cursor c = getContentResolver()
.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
int foundWithNumber = 0;
int foundWithOutNumber = 0;
if (c.moveToFirst()) {
int idHasNumber = c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
do {
boolean hasNumber = c.getInt(idHasNumber) > 0;
if (hasNumber) {
++foundWithNumber;
} else {
++foundWithOutNumber;
}
} while (c.moveToNext());
}
Log.d(TAG, "foundWithNumber: " + foundWithNumber);
Log.d(TAG, "foundWithOutNumber: " + foundWithOutNumber);
c.close();
}
The ouput on my phone is:
MainActivity D foundWithNumber: 184
D foundWithOutNumber: 303
So, I guess, you just looked at the wrong rows. ;)
You nead add Read contact permission in Android manifest
android.permission.READ_CONTACTS
I am looking to fetch complete contact detail of the owner (me profile - e.g. in Nexus). I found ContactsContract.Profile API which is available for API v14+.
I am successfully able to get display name, corresponding to which i further require contact number. To do all this, i am using following code
private void getSelfSimNumber() {
String displayName = null;
try {
Cursor c = this.getContentResolver().query(
ContactsContract.Profile.CONTENT_URI, null, null, null,
null);
int count = c.getCount();
boolean b = c.moveToFirst();
int position = c.getPosition();
if (count == 1 && position == 0) {
displayName = c.getString(c
.getColumnIndex(ContactsContract.Profile.DISPLAY_NAME));
if (Integer
.parseInt(c.getString(c
.getColumnIndex(ContactsContract.Profile.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = this.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " = ?", new String[] { displayName },
null);
while (pCur.moveToNext()) {
String ret = c.getString(0);
String ret1 = c.getString(1);
}
pCur.close();
}
}
c.close();
} catch (Exception e) {
}
}
The problem is I am unable to fetch contact number of "me" profile. If, suppose, I have total 3 contacts (including "me" profile) then total contacts available i am getting is only 2. The system is perhaps not considering "me" profile as a contact.
How to solve this problem and fetch contact number of "me" profile?
Thanks
I want to query the Contacts Database for phone number and if the selected contact has multiple numbers, I display the available numbers for the user to select one of them.
I have code in place that would pick up the default number of the selected contact.
Cursor cursor = null;
String phoneNumber = "";
try
{
Uri result = data.getData();
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for everything email
cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone.CONTACT_ID + "=?", new String[] { id },
null);
int pNumberIdx = cursor.getColumnIndex(Phone.NUMBER);
// let's just get the first email
if (cursor.moveToFirst())
{
phoneNumber = cursor.getString(pNumberIdx);
}
}
catch (Exception e)
{
}
finally
{
if (cursor != null)
{
cursor.close();
}
EditText emailEntry = (EditText) findViewById(R.id.pNumber);
emailEntry.setText(phoneNumber);
if (phoneNumber.length() == 0)
{
Toast.makeText(this, "No number found for contact.",
Toast.LENGTH_LONG).show();
}
}