views:

103

answers:

1

I have a custom dialog in my android application. I want to have in this dialog a field for choosing a phone number from contacts. This example describes such snippet. However for this example contact picker is created inside an activity and I do not know how to do this if I do not have activity (in case of dialog)

+1  A: 

This code solves the problem.

  public class ContactFieldActivity extends Activity {
private static final int PICK_NUMBER = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.field_contact);

    Button btnContacts = (Button)findViewById(R.id.btn_contacts);

    btnContacts.setOnClickListener(new OnClickListener() {  

        public void onClick(View arg0) {  
            Intent intent = new Intent(Intent.ACTION_PICK, Phones.CONTENT_URI);
            startActivityForResult(intent, PICK_NUMBER);
        }});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {  
         case (PICK_NUMBER):  
             if (resultCode == Activity.RESULT_OK) {  
                 Uri contactData = data.getData();  
                 Cursor c = managedQuery(contactData, null, null, null, null);  
                 if (c.moveToFirst()) {  
                     String number = c.getString(c.getColumnIndexOrThrow(Phones.NUMBER));
                     EditText edit = (EditText)findViewById(R.id.editNumber);
                     edit.setText(number);  
                 }  
             }  
             break;  
     }      
}   

}

Solvek