Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Contact Picker With Checkbox

There are a lot of discussions going on about the same subject, but after spending 4 hours here, I could not find a valid description or a link to make a Contact Picker with Checkbox.

I have an activity with DONE button and listview with checkbox. I have managed to show the contacts correctly. Now I want to return the selected contact phone numbers in a bundle (I think the best way) so that I can get the list of numbers in onActivityResult(). I am not sure of the way I am following is right or not.

Here is my code:

public class ContactPickerMulti extends ListActivity implements OnClickListener {

    // List variables
    public String[] Contacts = {};
    public int[] to = {};
    public ListView myListView;

    Button save_button;
    private TextView phone;
    private String phoneNumber;
    private Cursor cursor;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contacts_multi);

        // Initializing the buttons according to their ID
        save_button = (Button) findViewById(R.id.contact_done);

        // Defines listeners for the buttons
        save_button.setOnClickListener(this);

        Cursor mCursor = getContacts();
        startManagingCursor(mCursor);

        ListAdapter adapter = new SimpleCursorAdapter(
                this,
                android.R.layout.simple_list_item_multiple_choice,
                mCursor,
                Contacts = new String[] { ContactsContract.Contacts.DISPLAY_NAME },
                to = new int[] { android.R.id.text1 });

        setListAdapter(adapter);
        myListView = getListView();
        myListView.setItemsCanFocus(false);
        myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

    }

    private Cursor getContacts() {
        // Run query
        Uri uri = ContactsContract.Contacts.CONTENT_URI;
        String[] projection = new String[] { ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME };
        String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '"
                + ("1") + "'";
        String[] selectionArgs = null;
        String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
                + " COLLATE LOCALIZED ASC";

        return managedQuery(uri, projection, selection, selectionArgs,
                sortOrder);
    }

    public void onClick(View src) {
        Intent i;
        switch (src.getId()) {
        case R.id.contact_done:

            SparseBooleanArray selectedPositions = myListView
                    .getCheckedItemPositions();
            SparseBooleanArray checkedPositions = myListView
                    .getCheckedItemPositions();
            if (checkedPositions != null) {
                for (int k = 0; k < checkedPositions.size(); k++) {
                     if (checkedPositions.valueAt(k)) {
                          String name =
                                 ((Cursor)myListView.getAdapter().getItem(k)).getString(1);
                            Log.i("XXXX",name + " was selected");
                        }
                }
            }

            break;
        }

    }
}

I want to send the numbers as array or list. What is the best way to do this? Any help or leading to right path is highly appreciated.

like image 672
Ajmal Salim Avatar asked Sep 13 '12 19:09

Ajmal Salim


2 Answers

I use this code in onClick:

long[] id = getListView().getCheckedItemIds();//  i get the checked contact_id instead of position
        phoneNumber = new String[id.length];
        for (int i = 0; i < id.length; i++) {

            phoneNumber[i] = getPhoneNumber(id[i]); // get phonenumber from selected id

        }

        Intent pickContactIntent = new Intent();
        pickContactIntent.putExtra("PICK_CONTACT", phoneNumber);// Add checked phonenumber in intent and finish current activity.
        setResult(RESULT_OK, pickContactIntent);
        finish();

//

private String getPhoneNumber(long id) {
    String phone = null;
    Cursor phonesCursor = null;
    phonesCursor = queryPhoneNumbers(id);
    if (phonesCursor == null || phonesCursor.getCount() == 0) {
        // No valid number
        signalError();
        return null;
    } else if (phonesCursor.getCount() == 1) {
        // only one number, call it.
        phone = phonesCursor.getString(phonesCursor
                .getColumnIndex(Phone.NUMBER));
    } else {
        phonesCursor.moveToPosition(-1);
        while (phonesCursor.moveToNext()) {

            // Found super primary, call it.
            phone = phonesCursor.getString(phonesCursor
                    .getColumnIndex(Phone.NUMBER));
            break;

        }
    }

    return phone;
}


private Cursor queryPhoneNumbers(long contactId) {
    ContentResolver cr = getContentResolver();
    Uri baseUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
            contactId);
    Uri dataUri = Uri.withAppendedPath(baseUri,
            ContactsContract.Contacts.Data.CONTENT_DIRECTORY);

    Cursor c = cr.query(dataUri, new String[] { Phone._ID, Phone.NUMBER,
            Phone.IS_SUPER_PRIMARY, RawContacts.ACCOUNT_TYPE, Phone.TYPE,
            Phone.LABEL }, Data.MIMETYPE + "=?",
            new String[] { Phone.CONTENT_ITEM_TYPE }, null);
    if (c != null && c.moveToFirst()) {
        return c;
    }
    return null;
}

And the last onActivityResult of activity which you start PickContactsActivity

    // TODO Auto-generated method stub
    // super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) {

        if (requestCode == Constants.REQUEST_CODE_PICK_CONTACT) {


            if (data != null) {

                String[] temp = data.getStringArrayExtra("PICK_CONTACT");

            }
        }

    }

}
like image 111
Trung Nguyen Avatar answered Nov 03 '22 11:11

Trung Nguyen


When using startActivityForResult(newActivity) in the newActivity you must make a call to setResult(RESULT_OK) followed by finish() to close the Activity. Optionally you can include an Intent in the call to setResult(RESULT_OK, intent). The call to setResult() will lead to calling your implementation of onActivityResult() where you can handle the result of the Activity. So in your case you would just create an Intenet and add your array list to it using one of the putExtra() methods. That Intent will then be passed to onActivityResult() where you can extract that information. See Intent and Activity for more information.

like image 23
Jason Crosby Avatar answered Nov 03 '22 11:11

Jason Crosby