Android get phone number from contact list

前端 未结 4 724
耶瑟儿~
耶瑟儿~ 2020-12-21 10:29

I have these codes which basically use a ListView to display the names in the contact list and I want to get their phone number when click each single name:

         


        
4条回答
  •  萌比男神i
    2020-12-21 11:03

    First of all add this line in AndroidManifest.xml to take permission from user.

    
    

    implement the button of contact

            phoneContactsButtton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                // The below two line is needed to open the contact list of  mobile
                    Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                    startActivityForResult(contactPickerIntent,1);
    
                }
            });
    

    you have to override the onActivityResult() which will be written to the outside of onCreate() mehtod similar to this

        @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       }
    
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        switch (requestCode){
            case 1 :
                if (resultCode == Activity.RESULT_OK) {
                    Uri contactData = data.getData();
    
                    Cursor cur =  getContentResolver().query(contactData, null, null, null, null);
                    if (cur.getCount() > 0) {// thats mean some resutl has been found
                        if(cur.moveToNext()) {
                            String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                            String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                            Log.e("Names", name);
    
                            if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
                            {
    
                                Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null, null);
                                while (phones.moveToNext()) {
                                    String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                    Log.e("Number", phoneNumber);
                                }
                                phones.close();
                            }
    
                        }
                    }
                    cur.close();
                }
                break;
        }
    
    }
    

提交回复
热议问题