How to call Android contacts list?

前端 未结 13 2331
傲寒
傲寒 2020-11-22 02:50

I\'m making an Android app, and need to call the phone\'s contact list. I need to call the contacts list function, pick a contact, then return to my app with the contact\'s

13条回答
  •  礼貌的吻别
    2020-11-22 03:28

    -> Add a permission to read contacts data to your application manifest.
    
    
    
    -> 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);
            } catch (Exception e) {
                e.printStackTrace();
            }
                    break;
                }
            } else {
                Log.e("MainActivity", "Failed to pick contact");
            }
        }
    
    This will work check it out
    

提交回复
热议问题