Question

I have a edittext and a button,i want to open contact details on click of the button and user can select a contact from it.Then i need to put the mobile number of the selected contact in the edittext.How do i do that?Thanks

Was it helpful?

Solution

It's very simple. First you need to create edit text and button, then write the following code:

 private EditText e;
    private static final String DEBUG_TAG = "InviteActivity";
    private static final int CONTACT_PICKER_RESULT = 1001;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        e=(EditText)findViewById(R.id.editText1);      
    }

    public void doLaunchContactPicker(View view)
    {

        Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
                Contacts.CONTENT_URI);
        startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);

    }

    @Override
    protected void onActivityResult(int requestCode,int resultCode,Intent data)
    {
        if(resultCode==RESULT_OK)
        {
            switch(requestCode)
            {
            case CONTACT_PICKER_RESULT:
                Cursor cursor=null;
                String phone="";
                try
                { Uri result=data.getData();
                   String id=result.getLastPathSegment();
                    cursor=getContentResolver().query(Phone.CONTENT_URI,null, Phone.CONTACT_ID +"=?",new String[] {id},null);
                    int phoneIdx=cursor.getColumnIndex(Phone.NUMBER);
                    if(cursor.moveToFirst())
                    {
                    phone=cursor.getString(phoneIdx);
                    }
                    if(phone.equals(""))
                    {
                        Toast.makeText(getBaseContext(),"There is no phone number for that contac", Toast.LENGTH_LONG).show();
                    }
                    else
                    {
                    e.setText(phone);
                    }               
                }
                catch(Exception e)
                {
                    Toast.makeText(getBaseContext(),"There is no phone number for that contact", Toast.LENGTH_SHORT).show();
                }
                finally
                {
                    if(cursor!=null)
                    {
                        cursor.close();

                }//finally
                break;
            }//switch
        }//if

     else {
            Log.w(DEBUG_TAG, "Warning: activity result not ok");
        }
    }//on activity result

}//class

For Button properties give:

android:onClick="doLaunchContactPicker"

Don't forget to give uses-permisssions:

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

if this answer is useful please don't forget to accept..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top