0

I am using the code below to get a contact name and ID but I am not getting the phone number. How can I get the phone number from the code below?

ContentResolver contentResolver = getBaseContext().getContentResolver();

Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = {
        ContactsContract.Contacts._ID,
        ContactsContract.Contacts.DISPLAY_NAME,
        ContactsContract.Contacts.HAS_PHONE_NUMBER,
        ContactsContract.Contacts.STARRED,
        ContactsContract.Contacts.TIMES_CONTACTED,
        ContactsContract.Contacts.LAST_TIME_CONTACTED
};
String selection = String.format("%s > 0", ContactsContract.Contacts.HAS_PHONE_NUMBER);
String[] selectionArgs = null;
String sortOrder = String.format(
        "%s DESC, %s DESC, %S DESC, UPPER(%s) ASC",
        ContactsContract.Contacts.STARRED,
        ContactsContract.Contacts.TIMES_CONTACTED,
        ContactsContract.Contacts.LAST_TIME_CONTACTED,
        ContactsContract.Contacts.DISPLAY_NAME
);
Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, sortOrder);

if (cursor.getCount() > 0) {
    while (cursor.moveToNext()) {
        String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
        String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));


        if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {

            System.out.println("name : " + name + ", ID : ");

         }

        }
    }
    cursor.close();
}
Daniel
  • 2,355
  • 9
  • 23
  • 30
jason
  • 3,932
  • 11
  • 52
  • 123

3 Answers3

1

CModel.java

public class CModel {
String firstname;
String lastname;
String contactno;
String Imagepath;
int ID;
String contactid;

public String getCheck() {
    return Check;
}

String Check;

public String getContactid() {
    return contactid;
}

 public CModel(String fnm, String lastname, String userprofile, int ID,    String contactno, String Check) {
    this.firstname = fnm;
    this.lastname = lastname;
    this.Imagepath = userprofile;
    this.ID = ID;
    this.contactno = contactno;
    this.Check = Check;
}


public String getFirstname() {
    return firstname;
}

public String getLastname() {
    return lastname;
}

public String getContactno() {
    return contactno;
}

public String getImagepath() {
    return Imagepath;
}

public int getID() {
    return ID;
}

in your activity file call this method

private ArrayList<CModel> getcontact() {
ArrayList<CModel> contactlist = new ArrayList<CModel>;
try {
    Bitmap my_btmp = null;
    String profilepic;
    String phone = null;
    contactlist = new ArrayList<CModel>();
    ContentResolver cr = getContentResolver();
    String[] projection = new String[]{ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME};
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, projection, null, null,
            ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
    while (cur.moveToNext()) {
        String contactId = cur.getString(cur.getColumnIndex(ContactsContract.Data._ID));
        String displayName = cur.getString(cur.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
        Uri my_contact_Uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(contactId));
        InputStream photo_stream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(), my_contact_Uri);
        Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                new String[]{contactId}, null);
        while (pCur.moveToNext()) {
            phone = pCur.getString(
                    pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        }
        pCur.close();
        if (photo_stream != null) {
            BufferedInputStream buf = new BufferedInputStream(photo_stream);
            my_btmp = BitmapFactory.decodeStream(buf);
            profilepic = BitMapToString(my_btmp);
        } else {
            Bitmap bitmap = BitmapFactory.decodeResource(HomePage.this.getResources(), R.drawable.profilepic);
            my_btmp = bitmap;
            profilepic = BitMapToString(my_btmp);

        }
        String columns[] = {
                ContactsContract.CommonDataKinds.Event.START_DATE,
                ContactsContract.CommonDataKinds.Event.TYPE,
                ContactsContract.CommonDataKinds.Event.MIMETYPE,
        };
        String where =ContactsContract.CommonDataKinds.Event.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE + "' and " + ContactsContract.Data.CONTACT_ID + " = " + contactId;
        String[] selectionArgs = null;
        String sortOrder = ContactsContract.Contacts.DISPLAY_NAME;
        Cursor birthdayCur = cr.query(ContactsContract.Data.CONTENT_URI, columns, where, selectionArgs, sortOrder);
        if (birthdayCur.getCount() > 0) {
            if (birthdayCur.moveToFirst()) {
                do {

                    contactlist.add(new CModel(displayName, "", profilepic, 0, phone,"phone"));
                    boolean flag = con.comparedata(phone);

                } while (birthdayCur.moveToNext());

            }

        }
        birthdayCur.close();
    }
    cur.close();
} catch (Exception e) {
}
return contactlist;

}

Chetna
  • 154
  • 1
  • 1
  • 10
  • create fist CModel.java file and paste first code that is i already given, after that in your activity file in that paste getcontact() method and ctrl+space if any error is occur after that import all packages which is required. – Chetna Jun 25 '16 at 10:53
  • and then jst call getcontact() it will return list of contact in your phone, and also gives the permission for read contact – Chetna Jun 25 '16 at 10:53
  • But it takes a long time to load!! – jason Jun 25 '16 at 15:27
  • I just need the number .. My code loads really quickly but without number – jason Jun 25 '16 at 15:28
1

There is no phone Number in 'ContactsContract.Contacts' but 'ContactsContract.Contacts._ID' and 'ContactsContract.CommonDataKinds.Phone.CONTACT_ID' are same for each contact. Hence you can get phone number from 'ContactsContract.CommonDataKinds.Phone.CONTENT_URI' . Put this code inside your cursor's loop. Overall these are two queries but at least you know where to search. This should not take much time in execution.

Cursor phoneCursor = managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId , null, null);

        while (phoneCursor.moveToNext()) {
           String phone = phoneCursor.getString(phoneCursor
                    .getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));

        }
Shahbaz Hashmi
  • 2,631
  • 2
  • 26
  • 49
0

EDIT: This is my attempt at retrieving every phone number in 1 query but I'm unsure of the behavior if any contacts without phone numbers exist; in general it is best practice to always query the list of contacts that have phone numbers, and then query only those contacts numbers.

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));

    //Do something with each name and phone somewhere each time you loop through; in your provided code you seemed to be printing them out

}
phones.close();

For reference: Read all contact's phone numbers in android



This older post seemed helpful, based on some previous work I've done with writing to contacts: How to get contacts' phone number in Android

In general, the phone number is stored as a:

ContactsContract.CommonDataKinds.Phone.NUMBER 

So taking a snippet of the code you provided, I would edit roughly as so:

if (cursor.getCount() > 0) {
        while (cursor.moveToNext()) {
            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));


            ...
            ...

        cursor.close();
    } 

Of course you'll need to make sure in your query that you're grabbing the right segment of data from the contact (i.e. updating your projection), but that should hopefully point you in the right direction!

Community
  • 1
  • 1
gabe3vino
  • 313
  • 1
  • 3
  • 10
  • I get an error as this column does not exist.. Can you please write the entire query.. Because this query always crashes on system.. I have tried about a 100 times.... Please can you rewrite the entire query with phone no .. Thanks.. I really appreciate it. – jason Jun 27 '16 at 21:07
  • The ContactsContract database has various extensible tables, which you access via the URI you define in your query. These various tables are defined here: https://developer.android.com/reference/android/provider/ContactsContract.html So in the code you've provided, the URI is ContactsContract.Contacts.CONTENT_URI; However, this URI points at the Contacts table, so you don't have access to other tables within the ContactsContract db. So you need to do 1.multiple queries to different tables (sounds wrong) or 2.find a table within ContactsContract that has access to all the data you need. – gabe3vino Jun 28 '16 at 13:28
  • ^ And then modify your URI (and projection/selection) to access that proper table and retrieve the values you desire( number, name, and id). Also note that _id will generally just be the id of the contact within the table/contacts db, which I believe just relates to row number, so that may not be useful information. – gabe3vino Jun 28 '16 at 13:32
  • Through more research, it doesn't seem like theres a way to both retrieve a list of contacts, & their phone numbers with only 1 query. So the speed of execution will always be hindered by 2 queries. This will be timely since you aren't looking up a specific number but every single 1. – gabe3vino Jun 28 '16 at 13:41