I am using AlertDialog with setMultiChoiceItems to let the user select multiple items which is working fine. The problem is, next time the AlertDialog appears, it still has the items checked. I tried unchecking them by overriding onPrepareDialog but it is not working. This is my code:
@Override
protected Dialog onCreateDialog( int id )
{
String[] PROJECTION=new String[] { Contacts._ID,
Contacts.DISPLAY_NAME,
Phone.NUMBER};
String number = null;
String[] ARGS={String.valueOf(Phone.TYPE_MOBILE)};
c=managedQuery(Phone.CONTENT_URI,
PROJECTION, Phone.TYPE+"=?",
ARGS, Contacts.DISPLAY_NAME);
while (c.moveToNext()) {
number = c.getString(1);
names.add(number);
numbers.add(c.getString(2));
}
CharSequence[] cs = names.toArray(new CharSequence[names.size()]);
selection = new boolean[names.size()];
return new AlertDialog.Builder(this)
.setTitle("Pick Contacts")
.setMultiChoiceItems(cs,
selection, new DialogInterface.OnMultiChoiceClickListener(){
public void onClick(DialogInterface dialog, int whichButton,
boolean isChecked) {
if(isChecked){
names1.add(names.get(whichButton));
numbers1.add(numbers.get(whichButton));
isChecked = false;
}else{
names1.remove(names.get(whichButton));
numbers1.remove(numbers.get(whichButton));
}
}
})
.setPositiveButton( "OK", new DialogButtonClickHandler() )
.setNegativeButton( "Cancel", new DialogButtonClickHandler1() )
.create();
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
final AlertDialog alert = (AlertDialog)dialog;
final ListView list = alert.getListView();
for(int i = 0 ; i < list.getCount(); i++){
list.setItemChecked(i, false);
}
}
I tried checking all the items by using list.setItemsChecked(i,true) and its working but unchecking doesn't work. Any ideas?
To clear the checkboxes you simply have to go through your boolean array "selection" and set all entries to false.
I resolved this issue, and the code, which is presented below, already is applied in my app "Email Pictures Automatically":
https://play.google.com/store/apps/details?id=com.alexpap.EmailPicturesFree
This app is sending automatically every picture you make to a list of recipient emails. The functionality below is used to select a list of recipients, which will receive the pictures you make. Pictures are sending instantly.
Whole code is in EmailParametersActivity class. Works with minSdkVersion="5".
//class variables
private EditText emailSendEdit;
private EditText passwordEdit;
private EditText passwordRepeatEdit;
private EditText emailReceiveEdit;
//array with all contacts used in multiselection dialog. Each entry is a string - name and email separated with new line (\n)
public static String[] contactArray;
public static List<Integer> mSelectedItems = new ArrayList<Integer>(); //list of selected item IDs in multiselection dialog
//list of all contacts - name and email separated with new line (\n) for each entry (contact)
public static List<String> contactList;
//Some definitions in onCreate () method
emailSendEdit = (EditText) findViewById(R.id.send_email);
passwordEdit = (EditText) findViewById(R.id.password);
passwordRepeatEdit = (EditText) findViewById(R.id.password_repeat);
emailReceiveEdit = (EditText) findViewById(R.id.receive_email);
emailReceiveEdit.setOnLongClickListener(new myLongListener());
//end of onCreate() method
private class myLongListener implements View.OnLongClickListener {
@SuppressWarnings("deprecation")
@Override
public boolean onLongClick(View v) {
if (contactList == null || contactList.isEmpty()) {
//populate contacts sorted ahphabetically
contactList = populateContacts(EmailParametersActivity.this);
contactArray = new String[contactList.size()];
contactList.toArray(contactArray);
}
showDialog (0);
return false;
}
}
//We enter here only once, when the dialog is opened for the first time
@Override
protected Dialog onCreateDialog( int id )
{
mSelectedItems = new ArrayList();
return new AlertDialog.Builder( this )
.setTitle( "Contacts" )
.setMultiChoiceItems( contactArray, null, new DialogSelectionClickHandler() {
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
// If the the item is checked, add its ID to the selected IDs
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
// Else, if the ID of the item is already in the array, remove it
mSelectedItems.remove(Integer.valueOf(which));
}
}
})
.setPositiveButton( "OK", new DialogButtonClickHandler() )
.setNegativeButton("Cancel", new DialogButtonClickHandler() )
.create();
}
//We enter here every time the dialog is opened
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
//clear all previously selected item IDs
mSelectedItems.clear();
AlertDialog alert = (AlertDialog) dialog;
//get List of dialog checked items
ListView dialogListView = alert.getListView();
//uncheck all previously checked items
for(int i = 0 ; i < dialogListView.getCount(); i++){
dialogListView.setItemChecked(i, false);
}
}
//nothing to do here, we expect the result - list of checked items on click of OK button
public class DialogSelectionClickHandler implements DialogInterface.OnMultiChoiceClickListener
{
public void onClick( DialogInterface dialog, int clicked, boolean selected )
{
Log.i( "ME", contactArray[ clicked ] + " selected: " + selected );
}
}
//Here we take the result - the list of checked items, from which we construct the string with selected emails
//separated with coma
public class DialogButtonClickHandler implements DialogInterface.OnClickListener
{
public void onClick( DialogInterface dialog, int clicked )
{
switch( clicked )
{
case DialogInterface.BUTTON_POSITIVE:
String receiveEmailList = getSelectedItems();
String strReceiveEmail = emailReceiveEdit.getText().toString();
if (strReceiveEmail != null && strReceiveEmail.length() > 0){
if (receiveEmailList.length() > 0){
strReceiveEmail = strReceiveEmail + "," + receiveEmailList;
}
} else {
strReceiveEmail = receiveEmailList;
}
emailReceiveEdit.setText(strReceiveEmail);
break;
case DialogInterface.BUTTON_NEGATIVE:
dialog.dismiss();
break;
}
}
}
//we build the result. It is a string of selected items. Each item is a string with format - "name \n email".
//We take only the email in the result string;
protected String getSelectedItems(){
String emailList = "";
for( int i = 0; i < mSelectedItems.size(); i++ ){ //number of selected items in the dialog.
int j = (int) mSelectedItems.get(i); // get the ID of current selected item. It is equal to j;
Log.i( "ME", contactArray[ i ] + " selected: " + contactArray[ j ]);
String [] nameEmail = contactArray[ j ].split("\n"); //get email only
emailList = emailList + nameEmail[1] + ","; // createte a string with selected emails, separated with coma.
}
//remove the last coma in the string
if (emailList.length() > 1) {
emailList = emailList.substring(0, emailList.length() - 1);
}
//if nothing selected return emty string.
if (emailList.indexOf("@") < 1){
emailList = "";
}
return emailList;
}
And finally here is the function which gets conacts with names and emails
@SuppressLint("InlinedApi")
public List populateContacts(Context context) {
ContentResolver cr = context.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, "phonetic_name"); // "display_name_source");
List <String> contactList = new ArrayList <String> ();
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
//Get ID and Name form CONTACTS CONTRACTS
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//While we have cursor get the email
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = ?", new String[] { id }, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
contactList.add(name + "\n" + email);
}
emailCur.close();
}
}
cur.close();
//Sort contact list alphabetically - ascending (without fist item)
List<String> subList = contactList.subList(1, contactList.size());
Collections.sort(subList);
return contactList;
}