Search code examples
androidandroid-layoutandroid-intentandroid-emulator

Android - Showing Phonebook contacts and selecting one


How can I show the list of contacts in phonebook on a click of a button and then select one of the contacts from it and then retrieve its contact number?

I don’t want to make my custom list. Is there a way to use Android's built-in functionality?


Solution

  • TRY THIS-->

       setContentView(R.layout.main);
    
       contactNumber = (TextView)findViewById(R.id.contactnumber);
    
       Button buttonPickContact = (Button)findViewById(R.id.pickcontact);
       buttonPickContact.setOnClickListener(new Button.OnClickListener(){
    
       @Override
        public void onClick(View arg0) {
       // TODO Auto-generated method stub
    
    
       Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
       intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
       startActivityForResult(intent, 1);             
    
    
        }});
       }
    
       @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
    
       if(requestCode == RQS_PICK_CONTACT){
       if(resultCode == RESULT_OK){
        Uri contactData = data.getData();
        Cursor cursor =  managedQuery(contactData, null, null, null, null);
        cursor.moveToFirst();
    
          String number =       cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
    
          //contactName.setText(name);
          contactNumber.setText(number);
          //contactEmail.setText(email);
         }
         }
         }
         }
    

    EDIT XML ADDED;

          <?xml version="1.0" encoding="utf-8"?>
          <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:orientation="vertical" >
    
          <Button
            android:id="@+id/pickcontact"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Pick Contact" />
    
          <TextView
           android:id="@+id/contactnumber"
           android:layout_width="match_parent"
           android:layout_height="wrap_content" />
    
     </LinearLayout>