33

i want to pick a contact with it's number from my contacts list. i read a lot of solutions and research for couple weeks but all of articles didn't work properly. some codes like following:

Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);

// and in activityresult:

if (resultCode == Activity.RESULT_OK) {
            Uri contactData = data.getData();
            Cursor c =  managedQuery(contactData, null, null, null, null);
            if (c.moveToFirst()) {
              String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
              tv1.setText(name);
            }
          }

or this code for getting all contacts but i cant have the number of contacts:

String[] contacts = new String[] {People.NAME, People.NUMBER};       
Uri contentUri = People.CONTENT_URI;        
Cursor cursor = managedQuery(contentUri, contacts, null, null, null);                 
String textContacts = "";                 
if (cursor.moveToFirst()) {         
    String myname = null;         
    String mynumber = null;         
    do {          
        textContacts = textContacts + cursor.getString(cursor.getColumnIndex(People.NAME)) + " : " + cursor.getString(cursor.getColumnIndex(People.NUMBER)) + "\n";         
    } while (cursor.moveToNext()); 
tv1.setText(textContacts);
}

can anyone help me plz? my android is 2.3.3

aTa
  • 641
  • 2
  • 8
  • 20
  • does this query `Cursor c = managedQuery(contactData, null, null, null, null);` return you everything? did you check it? – Sergey Benner Feb 29 '12 at 09:23
  • you can also read this thread for examples https://groups.google.com/group/android-developers/browse_thread/thread/133816827efc8eb9/8671f76b4111f215?pli=1 – Sergey Benner Feb 29 '12 at 09:27
  • Try [android contact extractor](https://github.com/nitiwari-dev/android-contact-extractor). – Nitesh Tiwari May 13 '17 at 06:53

17 Answers17

61

Try following code it will help you:

  // You need below permission to read contacts
  <uses-permission android:name="android.permission.READ_CONTACTS"/>

  // Declare
  static final int PICK_CONTACT=1;

  Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
  startActivityForResult(intent, PICK_CONTACT);

  //code 
  @Override
 public void onActivityResult(int reqCode, int resultCode, Intent data) {
 super.onActivityResult(reqCode, resultCode, data);

 switch (reqCode) {
 case (PICK_CONTACT) :
   if (resultCode == Activity.RESULT_OK) {

     Uri contactData = data.getData();
     Cursor c =  managedQuery(contactData, null, null, null, null);
     if (c.moveToFirst()) {


         String id =c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));

         String hasPhone =c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

           if (hasPhone.equalsIgnoreCase("1")) {
          Cursor phones = getContentResolver().query( 
                       ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, 
                       ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id, 
                       null, null);
             phones.moveToFirst();
              cNumber = phones.getString(phones.getColumnIndex("data1"));
             System.out.println("number is:"+cNumber);
           }
         String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));


     }
   }
   break;
 }
 }
Sven Rojek
  • 5,476
  • 2
  • 35
  • 57
Dharmendra Barad
  • 949
  • 6
  • 14
  • 5
    This returns the 1st contact only. Any way to let me select 1 phone number from multiple phone numbers a contact has? – Ubaid Jan 27 '13 at 17:28
  • 1
    managedQuery is now deprecated, what the alternative ? Kindly update the answer – Gopal Singh Sirvi Feb 08 '17 at 10:06
  • 1
    @GopalSinghSirvi https://stackoverflow.com/questions/17739900/the-method-managedqueryuri-string-string-string-string-from-the-type-a replacement could be `getContentResolver().query()`, I'm not sure at all, you can test. –  Jun 24 '17 at 22:05
  • use ContactsContract.CommonDataKinds.Phone.NUMBER instead of 'data1' – Anuj Jindal Aug 08 '18 at 07:40
  • 1
    use ContactsContract.CommonDataKinds.Phone.NUMBER instead of "data1" AND ContactsContract.Contacts._ID instead of "_id" – Anuj Jindal Aug 08 '18 at 07:41
  • For some reason, this has issues working on Android10. – Jendorski Labs Jun 21 '21 at 22:31
  • on android 13 this method give all the information except for the phone number – Waseem Apr 04 '23 at 07:53
23

Use Intent.ACTION_PICK for accessing phone contact. Code as

Uri uri = Uri.parse("content://contacts");
Intent intent = new Intent(Intent.ACTION_PICK, uri);
intent.setType(Phone.CONTENT_TYPE);
startActivityForResult(intent, REQUEST_CODE);

Where

private static final int REQUEST_CODE = 1;

And use method onActivityResult() for access selected contact. Code as

@Override
    protected void onActivityResult(int requestCode, int resultCode,
            Intent intent) {
        if (requestCode == REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                Uri uri = intent.getData();
                String[] projection = { Phone.NUMBER, Phone.DISPLAY_NAME };

                Cursor cursor = getContentResolver().query(uri, projection,
                        null, null, null);
                cursor.moveToFirst();

                int numberColumnIndex = cursor.getColumnIndex(Phone.NUMBER);
                String number = cursor.getString(numberColumnIndex);

                int nameColumnIndex = cursor.getColumnIndex(Phone.DISPLAY_NAME);
                String name = cursor.getString(nameColumnIndex);

                Log.d(TAG, "ZZZ number : " + number +" , name : "+name);

            }
        }
    };
Arun Kumar
  • 2,874
  • 1
  • 18
  • 15
20

Add a permission to read contacts data to your application manifest.

<uses-permission android:name="android.permission.READ_CONTACTS"/>

Use Intent.Action_Pick in your Activity like below

Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
        startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);

Then Override the onActivityResult()

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // check whether the result is ok
        if (resultCode == RESULT_OK) {
            // Check for the request code, we might be usign multiple startActivityForReslut
            switch (requestCode) {
            case RESULT_PICK_CONTACT:
               Cursor cursor = null;
        try {
            String phoneNo = null ;
            String name = null;           
            Uri uri = data.getData();            
            cursor = getContentResolver().query(uri, null, null, null, null);
            cursor.moveToFirst();           
            int  phoneIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
            phoneNo = cursor.getString(phoneIndex); 

            textView2.setText(phoneNo);
            cursor.close()
        } catch (Exception e) {
            e.printStackTrace();
        }
                break;
            }
        } else {
            Log.e("MainActivity", "Failed to pick contact");
        }
    }

This will work check it out

ItzDavi
  • 443
  • 4
  • 13
Ravi
  • 281
  • 2
  • 4
4

If you want to pick a contact from contact list on click or focus event then copy this code and paste in Your activity.

  • FOCUS EVENT OF EDIT TEXT:

      phoneNo.setOnFocusChangeListener(new OnFocusChangeListener()
       {   public void onFocusChange(View v, boolean hasFocus) 
           {
              Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
              startActivityForResult(intent,PICK_CONTACT );//PICK_CONTACT is private static final int, so declare in activity class
        } });
    
  • A FUNCTION TO GET THE CONTACT NAME AND PHONE NO IS :

       public void onActivityResult(int reqCode, int resultCode, Intent data)
        {
          super.onActivityResult(reqCode, resultCode, data);
    
             switch(reqCode){
                case (PICK_CONTACT):
                  if (resultCode == Activity.RESULT_OK)
                  {
                      Uri contactData = data.getData();
                      Cursor c = managedQuery(contactData, null, null, null, null);
                   if (c.moveToFirst()) {
                   String id =   
                     c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
    
                   String hasPhone =
                   c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
    
                   if (hasPhone.equalsIgnoreCase("1")) {
                  Cursor phones = getContentResolver().query( 
                               ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, 
                               ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id, 
                               null, null);
                     phones.moveToFirst();
                     String phn_no = phones.getString(phones.getColumnIndex("data1"));
                     String name = c.getString(c.getColumnIndex(StructuredPostal.DISPLAY_NAME));
                    Toast.makeText(this, "contact info : "+ phn_no+"\n"+name, Toast.LENGTH_LONG).show();
    
                   }
                     }
                  }
             }
    }
    
Taslim Oseni
  • 6,086
  • 10
  • 44
  • 69
Pir Fahim Shah
  • 10,505
  • 1
  • 82
  • 81
3

You can try this solution as well if the contact does have multiple numbers

Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
            startActivityForResult(intent , REQUEST_CODE_ADDRESS_BOOK

);

and then for the activity result:

@Override
    public void onActivityResult(int reqCode, int resultCode, Intent data) {
        super.onActivityResult(reqCode, resultCode, data);

        switch (reqCode) {
            case (REQUEST_CODE_ADDRESS_BOOK):
                if (resultCode == Activity.RESULT_OK) {
                    Uri contactData = data.getData();
                    Cursor c =  getContentResolver().query(contactData, null, null, null, null);

                    c.moveToFirst();
                    String phoneNumber =  c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    c.close();
                }
                break;
        }
    }

And then, the number will be in phoneNumber variable.

Zeyad Assem
  • 1,224
  • 9
  • 6
3

Here is my answer for all, who are looking for the solution in Kotlin, do not get confused with "binding" word, this is just used for binding the view. On the click of "pickContact" , we are just opening Contacts App.

first add the permission in Manifest file.

<uses-permission android:name="android.permission.READ_CONTACTS"/>

val RESULT_PICK_CONTACT = 1

binding?.pickContact ->{
            val contactPickerIntent = Intent(
                Intent.ACTION_PICK,
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI
            )
            startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT)
        }

On Click of pickContact, we are opening Contacts app, And then overriding onActivityResult method,

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if (resultCode == Activity.RESULT_OK) {
        when (requestCode) {
            RESULT_PICK_CONTACT -> {
                var cursor: Cursor? = null
                try {
                    var phoneNo: String? = null
                    var name: String? = null
                    val uri: Uri? = data?.data
                    cursor = contentResolver.query(uri!!, null, null, null, null)
                    cursor?.moveToFirst()
                    val phoneIndex: Int =
                        cursor!!.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                    val phoneContactName: String =
                        cursor!!.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))
                    phoneNo = cursor?.getString(phoneIndex)
                    et_name.setText(phoneContactName) //setting the contacts name
                    mobile_number.setText(phoneNo) //setting the contacts phone number

                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    } else {
        Log.e("ActivityName", "Something went wrong")
    }
}

If you find any issue, just comment below, I will answer your query.

Jwala Kumar
  • 525
  • 7
  • 9
3

Here is what I implemented:

private String[] getContactList(){
    ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

    Log.i(LOG_TAG, "get Contact List: Fetching complete contact list");

    ArrayList<String> contact_names = new ArrayList<String>();

    if (cur.getCount() > 0) 
    {
        while (cur.moveToNext()) 
        {
            String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            if (cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER.trim())).equalsIgnoreCase("1"))
            {
                if (name!=null){
                    //contact_names[i]=name;

                    Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{id}, null);
                    while (pCur.moveToNext()) 
                    {
                        String PhoneNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        PhoneNumber = PhoneNumber.replaceAll("-", "");
                        if (PhoneNumber.trim().length() >= 10) {
                            PhoneNumber = PhoneNumber.substring(PhoneNumber.length() - 10);
                        }
                        contact_names.add(name + ":" + PhoneNumber);

                        //i++;
                        break;
                    }
                    pCur.close();
                    pCur.deactivate();
                    // i++;
                }
            }
        }
        cur.close();
        cur.deactivate();
    }

    String[] contactList = new String[contact_names.size()]; 

    for(int j = 0; j < contact_names.size(); j++){
        contactList[j] = contact_names.get(j);
    }

    return contactList;
}

You can call this function and maybe use an AutoCompleteTextView to display and pick contact name and 10 digit number. This function returns String array you can directly return the arrayList and remove the last for loop.

drulabs
  • 3,071
  • 28
  • 35
  • thank u KKD. your code works fine. but "Raju Barad"'s code works fine too. and because i want pick one contact then his code is work better for me. by the way thank u so much – aTa Mar 01 '12 at 12:04
  • I agree. Raju Barad's code seems better. You are welcome aTa. – drulabs Mar 01 '12 at 17:19
1
  • List item

this work for me

get Mobile Number AND name

 startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), TYPE_CONTACT);

case TYPE_CONTACT: uriContact = data.getData();

            String name=retrieveContactName();
            System.out.println("name = " + name);
            String number=retrieveContactNumber();
            System.out.println("number = " + number);
            break;

} }

private String retrieveContactNumber() {

    String contactNumber = null;

    // getting contacts ID
    Cursor cursorID = getContentResolver().query(uriContact,
            new String[]{ContactsContract.Contacts._ID},
            null, null, null);

    if (cursorID.moveToFirst()) {

        contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
    }

    cursorID.close();

    Log.d(TAG, "Contact ID: " + contactID);

    // Using the contact ID now we will get contact phone number
    Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},

            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
                    ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
                    ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,

            new String[]{contactID},
            null);

    if (cursorPhone.moveToFirst()) {
        contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    }

    cursorPhone.close();

    Log.d(TAG, "Contact Phone Number: " + contactNumber);
    return contactNumber;
}

private String retrieveContactName() {

    String contactName = null;

    // querying contact data store
    Cursor cursor = getContentResolver().query(uriContact, null, null, null, null);

    if (cursor.moveToFirst()) {

        // DISPLAY_NAME = The display name for the contact.
        // HAS_PHONE_NUMBER =   An indicator of whether this contact has at least one phone number.

        contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
    }

    cursor.close();

    Log.d(TAG, "Contact Name: " + contactName);

    return contactName;
}
Ashish Chaugule
  • 1,526
  • 11
  • 9
1

get mobile number and email address

//Get phone number

  name = getIntent().getExtras().getString("name");
  id = getIntent().getExtras().getString("contactid");

        Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},

                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
                        ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
                        ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,

                new String[]{id.toString()},
                null);
        String contactNumber = null;

   if (cursorPhone.moveToFirst()) {
       contactNumber =  cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
       System.out.println("contactnum"+contactNumber);
       }

  }
       cursorPhone.close();

//Get Email address

 Cursor emailCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                 null,
                ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{id}, null);

        if (emailCursor.moveToFirst()) {
            String phone = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
            int type = emailCursor.getInt(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
            String s = (String) ContactsContract.CommonDataKinds.Email.getTypeLabel(AddContactActivity.this.getResources(), type, "");
            etEmail.setText(phone);
        }
        emailCursor.close();
}
1

This code will work for mobile number contacts, not for email or something. i found this code simplest. let me know if there is any problem.

start activity with pick intent on phone data type:

findViewById(R.id.choose_contact_button).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
            Intent pickContact = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
            startActivityForResult(pickContact, PICK_CONTACT_REQUEST);
      }
 });

Now set onAcitivityResult();

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent){
        switch (requestCode){
            case PICK_CONTACT_REQUEST:
                if (resultCode == RESULT_OK){
                    Uri contactUri = intent.getData();
                    Cursor nameCursor = getContentResolver().query(contactUri, null, null, null, null);
                    if (nameCursor.moveToFirst()){
                        String name = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                        String number = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        ((EditText)findViewById(R.id.person_name)).setText(name);
                        ((EditText)findViewById(R.id.enter_mobile)).setText(number);
                        nameCursor.close();
                    }
                }
                break;
        }
    }
Nishant Bhakta
  • 2,897
  • 3
  • 21
  • 24
1

It's full code for select number from contacts by

companion object {
    const val RQ_CONTACTS = 232
}   




override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
            if (resultCode == RESULT_OK) {
                if (requestCode == RQ_CONTACTS) {
                    data?.let { contactPicked1(it) }
                }
                super.onActivityResult(requestCode, resultCode, data)

            }
}

private fun getContactByNumber() {
            val intent = Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI)
            intent.setDataAndType(ContactsContract.Contacts.CONTENT_URI, ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            startActivityForResult(intent, RQ_CONTACTS)
}

private fun contactPicked1(data: Intent) {
            var cursor: Cursor? = null
            try {
                val uri = data.data
                cursor = requireActivity().contentResolver.query(uri, arrayOf(ContactsContract.CommonDataKinds.Phone.NUMBER) , null, null, null)
                if (cursor.moveToFirst()) {
                    val phoneNo: String? =
                        cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER))
                    //Your code Example: phoneNo?.let{dialogAddFriend.setTextToField(it) }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                cursor?.close()
            }
}
Serega Maleev
  • 403
  • 5
  • 6
0

This may help you:

public void onActivityResult(int reqCode, int resultCode, Intent data) {
        super.onActivityResult(reqCode, resultCode, data);

        try {
            if (resultCode == Activity.RESULT_OK) {
                Uri contactData = data.getData();
                Cursor cur = managedQuery(contactData, null, null, null, null);
                ContentResolver contect_resolver = getContentResolver();

                if (cur.moveToFirst()) {
                    String id = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
                    String name = "";
                    String no = "";

                    Cursor phoneCur = contect_resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);

                    if (phoneCur.moveToFirst()) {
                        name = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                        no = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    }

                    Log.e("Phone no & name :***: ", name + " : " + no);
                    txt.append(name + " : " + no + "\n");

                    id = null;
                    name = null;
                    no = null;
                    phoneCur = null;
                }
                contect_resolver = null;
                cur = null;
                //                      populateContacts();
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            Log.e("IllegalArgumentException::", e.toString());
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("Error :: ", e.toString());
        }
    }
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
Abhishek
  • 682
  • 6
  • 17
0

Without manifest or run time permissions you can try this.

To pickup the name and contact number both from contacts app. By this code the contact app will also show the number below the contact name.

The code is to pick only single name and number from contacts app.

private void openContactSelectionIntent() {
        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
        startActivityForResult(Intent.createChooser(intent, "Select Contact"), RC_SELECT_CONTACT);
    }

And here is onActivityResult method's code

Uri uri1 = data.getData();
                Cursor c = managedQuery(uri1, null, null, null, null);
                if (c.moveToFirst()) {
                    String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    System.out.println("name is: " + name);

                }



                Cursor cursor = getContentResolver().query(uri1, null, null, null, null);
                if (null == cursor) return;
                try {
                    while (cursor.moveToNext()) {
                        String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                        System.out.println("number is "+number);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    cursor.close();
                }
Gopal Singh Sirvi
  • 4,539
  • 5
  • 33
  • 55
0
if (requestCode == RESULT_CONTACTS && resultCode == Activity.RESULT_OK) {
            Uri uri;
            Cursor cursor1, cursor2;
            String TempNameHolder, TempNumberHolder, TempContactID, IDresult = "";
            int IDresultHolder;
            uri = data.getData();
            cursor1 = getContentResolver().query(uri, null, null, null, null);
            if (cursor1.moveToFirst()) {
                TempNameHolder = cursor1.getString(cursor1.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                mToMeetName = TempNameHolder.trim();
                TempContactID = cursor1.getString(cursor1.getColumnIndex(ContactsContract.Contacts._ID));
                IDresult = cursor1.getString(cursor1.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                IDresultHolder = Integer.valueOf(IDresult);
                if (IDresultHolder == 1) {
                    cursor2 = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + TempContactID, null, null);
                    while (cursor2.moveToNext()) {
                        TempNumberHolder = cursor2.getString(cursor2.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        mToMeetName = TempNumberHolder.trim();
                        mEditTextToMeet.setText(TempNumberHolder + "( " + TempNameHolder + " )");
                        //number.setText(TempNumberHolder);
                    }
                }
            }
        }
Ashwin H
  • 695
  • 7
  • 24
0

You can use LiveData for get Name and number from Contact list, Also check Contact permission.

ReadContactsViewModel

public class ReadContactsViewModel extends AndroidViewModel {
private MutableLiveData<ArrayList<Contat>> contactList;

public ReadContactsViewModel(@NonNull Application application) {
    super(application);
}


public MutableLiveData<ArrayList<Contat>> getContacts(Context context) {
    if (contactList == null) {
        String phoneNumber;
        ArrayList<Contat> savedContacts = new ArrayList<>();
        Contat savedContact;
        ContentResolver cr = context.getContentResolver();
        ArrayList<String> idList = new ArrayList<>();
        if (cr != null) {
            Cursor cur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, "UPPER(" + ContactsContract.Contacts.DISPLAY_NAME + ") ASC");
            if (cur != null) {
                while (cur.moveToNext()) {


                    phoneNumber = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    if (phoneNumber.length() > 9) {
                        savedContact = new Contat();
                        phoneNumber = phoneNumber.replaceAll("\\s+", "");
                        String id = phoneNumber.substring(phoneNumber.length() - 7);//last 7 digits of numbers
                        String name = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                        String photoThumb = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI));
                        savedContact.setNumber(phoneNumber);
                        savedContact.setName(name);

                        if (!idList.contains(id)) {
                            savedContacts.add(savedContact);
                            idList.add(id);
                        }
                    }
                }

                cur.close();
                idList.clear();
            }

        }

        contactList = new MutableLiveData<>();
        contactList.setValue(savedContacts);
    }
    return contactList;
}

Now you can get or either send this savedContactList to server, i also used permission TedPermission Library you can use anyone you like

    private void syncContacts() {
    ReadContactsViewModel readContactsViewModel = ViewModelProviders.of(this)
            .get(ReadContactsViewModel.class);

    Observer<ArrayList<Contat>> readContactsObserver =
            new Observer<ArrayList<Contat>>() {
                @Override
                public void onChanged(@Nullable ArrayList<Contat> savedContactList) {
                    assert savedContactList != null;
                    for (int i = 0; i < savedContactList.size(); i++) {
                        Contat savedContact = savedContactList.get(i);

                        contactPostList.add(new Contat(savedContact.getName(), savedContact.getNumber()));
                    }
                    youractiviy.this.postContactsToServer();

                }
            };
    contactPermissionListener = new PermissionListener() {
        @Override
        public void onPermissionGranted() {


            readContactsViewModel.getContacts(youractiviy.this)
                    .observe(youractiviy.this,
                            readContactsObserver);


        }

        @Override
        public void onPermissionDenied(ArrayList<String> deniedPermissions) {

        }
    };

    TedPermission.with(this).setPermissionListener(contactPermissionListener).setDeniedMessage(R.string.permission_denied).setPermissions(Manifest.permission.READ_CONTACTS).check();
}
Ahmad
  • 201
  • 2
  • 12
0

Kotlin | Updated August.2022

Firstly add Read Contact Permission

<uses-permission android:name="android.permission.READ_CONTACTS" />

Then add Use Intent to pick up contact, here binding is used to bind with view.

binding.familyRelativeTv -> {
            val contactPickerIntent = Intent(
                Intent.ACTION_PICK,
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI
            )
            startForResult.launch(contactPickerIntent)
        }

then

private val startForResult =
    registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == RESULT_OK){
            var cursor: Cursor? = null
            try {
                val phoneNo: String?
                val uri: Uri? = result.data?.data
                cursor = activity?.contentResolver?.query(uri!!, null, null, null, null)
                cursor?.moveToFirst()
                val phoneIndex: Int =
                    cursor!!.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                phoneNo = cursor.getString(phoneIndex)
                binding.familyRelativeTv.text = phoneNo //setting phone number in textview

            } catch (e: Exception) {
                e.printStackTrace()
            }
            cursor?.close()
        }
    }
Aditya Cheke
  • 53
  • 2
  • 4
0

try following code,

Intent intent = new Intent(Intent.ACTION_PICK);                          
intent.setType(ContactsContract.Contacts._ID);                          
startActivityForResult(intent, PICK_CONTACT);                          

 public void onActivityResult(int requestCode, int resultCode, Intent intent)  
 {          
    if (requestCode == PICK_CONTACT)         
    { 
          Cursor cursor =  managedQuery(Email.CONTENT_URI, null, Email.CONTACT_ID +  " = " + intent.getData(), null, null);                 
          cursor.moveToNext();                 
          String contactId = cursor.getString(cursor.getColumnIndex(Email._ID));
          String  name = cursor.getString(cursor.getColumnIndexOrThrow(Email.DATA1));                   
          Toast.makeText(this, "Contect LIST  =  "+name, Toast.LENGTH_LONG).show();            
   }
}
Lucifer
  • 29,392
  • 25
  • 90
  • 143