ListView with CHOICE_MODE_SINGLE. Select up to one choice - android

I have a multi choice list inside an AlertDialog.
Reading the documentation of CHOICE_MODE_SINGLE, I thought that you could have one or no item checked but for me it behaves like a Radio Button List. It starts with all checkboxes unchecked by default by once I check one, it cannot be unchecked.
I tried hacking it with manual setItemChecked inside onClick but that is not a solution.
What am I doing wrong? How to achieve one or no checkbox in a ListView?
Here's my code:
builder.setMultiChoiceItems(titles, new boolean[titles.length], new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int position, boolean b) {
if (selectedId == -1) {
selectedId = position;
} else {
if (selectedId == position) {
mDialog.getListView().setItemChecked(position, false);
selectedId = -1;
} else {
mDialog.getListView().setItemChecked(selectedId, false);
selectedId = position;
}
}
}
});
mDialog = builder.create();
mDialog.getListView().setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);

your code isn't working because the method that you are using, setItemChecked, doesn't change the selected state when receive a false and is working on CHOICE_MODE_SINGLE, which is the normal behaviour of a group of radio buttons. You can see it by yourself with "Go To Implementation" in Android Studio (Ctrl + RightClick over the method).
Also, it's not recommended to use checkboxes for a single choice selector as it will confuse your users. You can easily get radio buttons replacing setMultipleChoiceItems by setSingleChoiceItems. It also apply the single choice mode to your ListView, so you can get rid of your last line.
To allow the user to perform an empty selection with radio buttons you have mainly 2 options:
Add an extra items to your list representing the empty selection option. Label it as "None", "Uncheck" or something similar
Add an extra button to your dialog to dismiss the dialog and return an empty selection.
Here you have a sample of implementation of the first option adding dynamically the empty item for a better re-usability ;)
Screenshot
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String title = "Select your favourite language";
String[] items = {"English", "Spanish", "Chinese", "Java"};
String emptyItemTitle = "NONE OF THEM";
int initialSelection = 0;
showSingleChoiceDialogWithNoneOption(title, items, initialSelection, emptyItemTitle);
}
private void showSingleChoiceDialogWithNoneOption(String title, final String[] titleItems, int initialSelection, String emptyItemTitle ) {
final String[] extendedItems = addEmptyItem(titleItems, emptyItemTitle);
final int[] selectedPosition = {initialSelection};
new AlertDialog.Builder(this)
.setTitle(title)
.setSingleChoiceItems(extendedItems, initialSelection, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selectedPosition[0] = which;
Log.d("MyTag", String.format("Selected item '%s' at position %s.", extendedItems[which], which));
}
})
.setNegativeButton("Cancel", null)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d("MyTag", String.format("Confirmed the selection of '%s' at position %s.", extendedItems[selectedPosition[0]], selectedPosition[0]));
onSelectionConfirmed(selectedPosition[0]);
}
})
.show();
}
#NonNull
private String[] addEmptyItem(String[] titleItems, String emptyTitle) {
String[] tempArray = new String[titleItems.length + 1];
tempArray[0] = emptyTitle;
System.arraycopy(titleItems, 0, tempArray, 1, titleItems.length);
return tempArray;
}
private void onSelectionConfirmed(int position) {
if (position==0){
//Handle your empty selection
}else{
//Selected item at position
}
}
}

Related

ListView updates the entry only when the application is restarted again

In this application, I have a listview and a sqlitedatabase. There is a floating action button which on clicking displays a dialog box containing two edittext one for name and another for number. The problem is that the after clicking on the add option of the dialog box the entry is not shown on the listview. But when the activity is destroyed and onCreate is called again on the activity , the entry is shown.
I tried using adapter.notifyDataSetChanged() but it doesn't work. The code is shown below :
Code
public class DetailsActivity extends AppCompatActivity {
private DatabaseManager manager;
private ListView listView;
private SimpleCursorAdapter adapter;
final String[] from=new String[] {UserDatabase.NAME,UserDatabase.NUMBER};
final int[] to=new int[] {R.id.nameDisplay,R.id.phoneDisplay};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
manager = new DatabaseManager(getApplicationContext());
manager.open();
Cursor cursor=manager.fetch();
listView = (ListView) findViewById(R.id.listViewId);
listView.setEmptyView(findViewById(R.id.empty));
adapter = new SimpleCursorAdapter(getApplicationContext(),
R.layout.row_item, cursor, from, to, 0);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(DetailsActivity.this);
LayoutInflater inflater = DetailsActivity.this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.custom_dialog, null);
dialogBuilder.setView(dialogView);
final EditText name = (EditText) dialogView.findViewById(R.id.dialogEditNmID);
final EditText phone = (EditText) dialogView.findViewById(R.id.dialogEditPhID);
dialogBuilder.setTitle("Add Details");
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!TextUtils.isEmpty(name.getText().toString()) &&
!TextUtils.isEmpty(phone.getText().toString())) {
/*adapter.notifyDataSetChanged();
manager.insert(name.getText().toString(), phone.getText().toString());
Toast.makeText(getApplicationContext(),
"Added " + name.getText().toString(), Toast.LENGTH_SHORT).show();*/
insertData(name.getText().toString(),phone.getText().toString());
} else {
Toast.makeText(getApplicationContext(),
"Empty field(s)", Toast.LENGTH_SHORT).show();
}
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog b = dialogBuilder.create();
b.show();
// listView.setAdapter(adapter);
//adapter.notifyDataSetChanged();
}
});
}
public void insertData(String fname,String phnumber){
manager.insert(fname,phnumber);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
Some of the statements are commented because I tried to get the desired result but couldn't get it.
There's a couple things here you have to change. Taking a look at this code:
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!TextUtils.isEmpty(name.getText().toString()) && !TextUtils.isEmpty(phone.getText().toString())) {
adapter.notifyDataSetChanged();
manager.insert(name.getText().toString(), phone.getText().toString());
Toast.makeText(getApplicationContext(), "Added " + name.getText().toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Empty field(s)", Toast.LENGTH_SHORT).show();
}
}
});
When you click the "Add" button, right away you call adapter.notifyDataSetChanged();. In your case, you are only supposed to call that after you have added items to listView, but you haven't added anything yet.
You insert into your database using manager.insert(name.getText().toString(), phone.getText().toString());, but you don't update listView with your newly added data. You need to insert that data to the database, and then also add that data to listView.
Now you can call adapter.notifyDataSetChanged();.
I would recommend that when you want to insert into your database, create a method which will insert the data, add the new data to the listView, and then tell the adapter to refresh.
Edit
Regarding your recent edit, there's still a few things that need to be taken care of.
You should not have listView.setAdapter(adapter) in the method. You had it right the first time (in onCreate() but before the dialog builder).
You call manager.insert(fname,phnumber);, but still do not add the newly inserted data to listView.
Here's pseudocode for what you should have in your method:
public void insertData(String fname,String phnumber){
manager.insert(fname,phnumber);
// Code to add the data you just inserted into the manager above to `listView`.
adapter.notifyDataSetChanged();
}
Remember, adapter.notifyDataSetChanged(); only updates listView if there's changes to listView, and as of right now you haven't added/deleted/modified listView.
After you insert the entries in your database, you should fetch the data again so that your list has the newest entry. So you can either modify your code to be able to add a data point to the list you are passing to the adapter or refetch the data from the database after insertions and before notifyDatasetChanged().
i have did some changes into the code please try it and let me know if it is helpful or not
public class DetailsActivity extends AppCompatActivity {
private DatabaseManager manager;
private ListView listView;
private SimpleCursorAdapter adapter;
final String[] from=new String[] {UserDatabase.NAME,UserDatabase.NUMBER};
final int[] to=new int[] {R.id.nameDisplay,R.id.phoneDisplay};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
manager = new DatabaseManager(getApplicationContext());
manager.open();
listView = (ListView) findViewById(R.id.listViewId);
listView.setEmptyView(findViewById(R.id.empty));
adapter = new SimpleCursorAdapter(getApplicationContext(),R.layout.row_item, cursor, from, to, 0);
//adapter.notifyDataSetChanged();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(DetailsActivity.this);
LayoutInflater inflater = DetailsActivity.this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.custom_dialog, null);
dialogBuilder.setView(dialogView);
final EditText name = (EditText) dialogView.findViewById(R.id.dialogEditNmID);
final EditText phone = (EditText) dialogView.findViewById(R.id.dialogEditPhID);
dialogBuilder.setTitle("Add Details");
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!TextUtils.isEmpty(name.getText().toString()) &&
!TextUtils.isEmpty(phone.getText().toString())) {
adapter.notifyDataSetChanged();
manager.insert(name.getText().toString(), phone.getText().toString());
Toast.makeText(getApplicationContext(),
"Added " + name.getText().toString(), Toast.LENGTH_SHORT).show();
Cursor cursor = manager.fetch();
listView.setAdapter(adapter);
} else {
Toast.makeText(getApplicationContext(),
"Empty field(s)", Toast.LENGTH_SHORT).show();
}
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog b = dialogBuilder.create();
b.show();
// listView.setAdapter(adapter);
//adapter.notifyDataSetChanged();
}
});
}}
Try to use notifyDataSetChanged after insert operation. In all place where you call(try to call) notify manager data isn't change yet.

Android select spinner item into alert dialog and text button disappear

I have a listview with a series of elements.
The click on an item of listview shows me a custom dialog.
In custom dialog I have a layout with:
A spinner
Two buttons (OK / ANNULLA)
This is the normal situation:
When I select the spinner, he shows a list of items.
When I select an item from the spinner, the text that was present on the buttons disappear in this way:
ps: this does not happen on Android 6.0, but it happens in the lower versions (such as 5.0)
The Code:
public void showDialogTagAssociation (Activity activity, Handler handler,
String msg, final MyOperator elemento, final BluetoothDevice device,
final int position){
mHandler = handler;
//-----------------------------------------------------
// DIALOG
dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
//-----------------------------------------------------
//---------------------------------------------------------------------
// LAYOUT
dialog.setContentView(R.layout.alert_dialog_custom_tag);
**// Spinner element
spinner = (Spinner) dialog.findViewById(R.id.spinner);**
// Spinner click listener
**spinner.setOnItemSelectedListener(new OnSpinnerItemClicked());**
//---------------------------------------------------------------------
//----------------------------------------------------------------------
// BUTTON OK
dialogButtonOK = (Button) dialog.findViewById(R.id.acd_btn_ok);
dialogButtonOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "Devo assegnare il tag al nome....");
Log.d(TAG, "Nome: " +tmpNome+"\n" +
"TAG: "+device.getName()+" - "+device.getAddress());
dialog.dismiss();
}
});
// BUTTON ANNULLA
dialogButtonNO = (Button) dialog.findViewById(R.id.acd_btn_no);
dialogButtonNO.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
//----------------------------------------------------------------------
dialog.show();
}
**private class OnSpinnerItemClicked implements android.widget.AdapterView.OnItemSelectedListener {**
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
//NOME
tmpNome = parent.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
Thanks for the future help
Remove that piece of code:
spinner.setOnItemSelectedListener(new OnSpinnerItemClicked());
and the thing which you want will still work.

Add a Multiple-Delete option in ListView Android

In my app, information like file names are stored in the externally storage. They are then implemented into the app with the help of ListView. I can delete files individually with OnItemLongClickListener() but I want to select multiple files in ListView and then click a Delete button. How can I do this? My MainActivity file is below:
public class MainActivity extends AppCompatActivity {
ArrayList<FileName> filenames;
ListViewAdapter adapter;
ListView lv_filenames;
public Handler handler;
private String _path = Environment.getExternalStorageDirectory() + "/sample_directory/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditorManager manager = new EditorManager(getApplicationContext());
manager.CreateNewDirectory();
lv_filenames = (ListView) findViewById(R.id.list);
handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
filenames = manager.GetList();
adapter = new ListViewAdapter(getApplicationContext(), R.layout.listView, filenames);
lv_filenames.setAdapter(adapter);
lv_filenames.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int file_name, long l) {
final File deleteFile = new File(_path + filenames.get(file_name).getName());
final String tempFileName = filenames.get(file_name).getName() + " is deleted";
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Delete File");
builder.setMessage("Do you really want to delete this file?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
boolean deleted = deleteFile.delete();
if (deleted) {
Toast.makeText(getApplicationContext(), tempFileName, Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// Do nothing.
}
});
builder.create();
AlertDialog dialog = builder.create();
dialog.show();
return false;
}
});
}
}
I deleted the extra code. Thanx for helping!
PS -
I heard that in Android 4.4 + files can't be deleted like this. What should I do?
EDIT -
I have seen those answers. But I want to create a button on whose click the check/uncheck buttons would be available. How can I do that? I want the Check/Uncheck buttons to be visible only when I click delete button. Also the other answers are a bit confusing.
I would have a button with a edit or delete icon and have it change the ListView to one with checkboxes in each view. Either make a new ListView with a new Adapter or just tell adapter and set a boolean in it, and then dataSetChange the Adapter.
I fixed my problem. I use a SparseBooleanAdapter to register the delete options.Then I press delete button to delete them.

How to get setMultiChoiceItems checkboxes in dialogs to update when you use a Sqlite Cursor

When implementing setMultiChoiceItems with a cursor, you have to specify an isCheckedColumn.
The problem, as articulated on other sites, is that when users select an item from the list the checkbox does not update. Some have suggested updating the SqLite table each time a user selects an item, but this did not work in my application. Here is the solution I came up with.
This is what I came up with:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int myDialogChoice = getArguments().getInt("whichDialog");
mSelectedItems = new ArrayList(); // Where we track the selected items
mCurrentFavoritesSelection = new ArrayList();
myDataBaseAdapter = new AthleteDbAdapter(getActivity());
// int myAthleteId;
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
switch(myDialogChoice) {
case Select_From_Favorites:
myCursorFromSqLite = myDataBaseAdapter.fetchAllFavorites(getActivity());
// You need a Primative Boolean Array to specify which items were selected last time.
boolean[] booleanPrimativeArray = new boolean[myCursorFromSqLite.getCount()];
final ArrayList mArrayListOfIDs = new ArrayList();
ArrayList<Boolean> myBooleanList = new ArrayList<Boolean>();
// This array will be the choices that appear in the Dialog.
ArrayList<String> mArrayListOfNames = new ArrayList<String>();
myCursorFromSqLite.moveToFirst();
/* Populate Arrays
*
*/
int iCount = 0;
while(!myCursorFromSqLite.isAfterLast()) {
// put _id's from SqLite data into an array.
mArrayListOfIDs.add(Integer.valueOf(
myCursorFromSqLite.getString(myCursorFromSqLite.getColumnIndex(KEY_ROWID))));
// put series of booleans into Primative Array depending upon whether user selected them last time.
if(Integer.valueOf(myCursorFromSqLite.getString(myCursorFromSqLite.getColumnIndex("checked"))) == 1){
booleanPrimativeArray[iCount] = true;
mSelectedItems.add(
Integer.valueOf(myCursorFromSqLite.getString(myCursorFromSqLite.getColumnIndex(KEY_ROWID)))
);
// I kept track of what selections from last time were.
mCurrentFavoritesSelection.add(
Integer.valueOf(myCursorFromSqLite.getString(myCursorFromSqLite.getColumnIndex(KEY_ROWID)))
);
} else booleanPrimativeArray[iCount] = false;
iCount++;
mArrayListOfNames.add(myCursorFromSqLite.getString(myCursorFromSqLite.getColumnIndex("fullName")));
myCursorFromSqLite.moveToNext();
}
// Change the ArrayList of names to a Char Sequence
CharSequence[] charSeqOfNames = mArrayListOfNames.toArray(new CharSequence[mArrayListOfNames.size()]);
try{
myCursorFromSqLite.close();
} catch (Throwable t) {
Log.e(APP_TAG,"Error closing myCursorFromSqLite Cursor " + t);
}
builder.setTitle(R.string.pick_athletes)
.setMultiChoiceItems(charSeqOfNames, booleanPrimativeArray,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
// If the user checked the item, build an array containing the selected items _id's.
mSelectedItems.add((Integer) mArrayListOfIDs.get(which));
} else if (mSelectedItems.contains((Integer) mArrayListOfIDs.get(which))) {
// Else, if the user changes his mind and de-selects an item, remove it
mSelectedItems.remove((Integer) mArrayListOfIDs.get(which));
}
}
})
// Set the action buttons
.setPositiveButton(R.string.pullathletesbutton, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
Log.d(APP_TAG,"Call something");
mListener.onDialogPositiveClick(PickListDialog.this, mSelectedItems, mCurrentFavoritesSelection);
}
})
.setNegativeButton(R.string.cancelbutton, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
This worked well. The user can change his mind without affecting the underlying database and the checkmarks update properly. Once the user has finalized his choices, he hits the "positive" button and the database is updated.

Toggling check boxes in MultiChoice AlertDialog in android

Hi,
I have created the MultiChoice
AlertDialog The AlertDialog has five
list items with checkboxes. When I
check First checkbox, w.r.t this the
if the other checkboxes in the list
are checked they shud be unchecked
automatically and vice versa.
I am checking the isChecked status
in the onClick method of
OnMultiChoiceClickListener() and calling the
showDialog(DIALOG_MULTIPLE_CHOICE); by updating boolean[]
checkedItems; to recreate the
Dialog, But I am unable to achieve it.
If you any suggestions please direct
me to right way.
Is there any way to recreate the AleartDialog onClick event of the radio button click.
Some Sample Code below:
case DIALOG_MULTIPLE_CHOICE:
final String[] lJobTypes = { "Item1", "Item2", "Item3","Item4", "Item5" };
return new AlertDialog.Builder(JoblistPage.this)
// .setIcon(R.drawable.logo)
.setTitle("Title Here")
// .setCustomTitle(m_Title)
.setMultiChoiceItems(lTypes, m_Selections,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog,int whichButton, boolean isChecked) {
/* User clicked on a check box do some stuff */
if (isChecked) {
m_CheckCount++;
//Toggle the Radio button Check status
} else {
m_CheckCount--;
}
}
}).setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
}).create();
Regards
Vinayak
Don't recreate the dialog, just toggle the checkboxes within the current dialog. Your onMultiChoiceClickListener can keep track of the currently active checkbox (if any) and uncheck it when another is selected. Here's a complete tested, working example:
package com.stackoverflow.beekeeper;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;
public class StackOverflowTest extends Activity {
/** Called when the activity is first created. */
#Override public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
private int mSelected = -1;
#Override protected void onResume() {
super.onResume();
final Builder build = new Builder(this);
build.setTitle("List selection");
build.setCancelable(true);
final String[] strings = new String[]{"Cow", "Horse", "Goat"};
final OnMultiChoiceClickListener onClick =
new OnMultiChoiceClickListener() {
#Override public void onClick(final DialogInterface dialog,
final int which, final boolean isChecked) {
if (isChecked) {
if ((mSelected != -1) && (mSelected != which)) {
final int oldVal = mSelected;
final AlertDialog alert = (AlertDialog)dialog;
final ListView list = alert.getListView();
list.setItemChecked(oldVal, false);
}
mSelected = which;
} else
mSelected = -1;
}
};
build.setMultiChoiceItems(strings, null, onClick);
build.setPositiveButton("Done", new OnClickListener() {
#Override public void onClick(final DialogInterface dialog,
final int which) {
String message = null;
if (mSelected == -1)
message = "You didn't select anything.";
else
message = "You selected '" + strings[mSelected] + "'";
Toast.makeText(StackOverflowTest.this, message, Toast.LENGTH_LONG).show();
}
});
build.show();
}
}
One thing to watch for: you must specify "null" for the "checkedItems" parameter in your "setMultiChoiceItems" call -- otherwise the "setItemChecked" calls won't work as expected. It would end up using that array to store the checked state, and "setItemChecked" would'nt update it correctly, so everything would get confused. Odd, but true.
I was struggling with this for quite some time. I maintain an array of the "checked" status of each of the items and change that value while visually changing the setItemChecked value. Then when the done button is clicked I iterate through "checked" to save the values to my db.
builder.setMultiChoiceItems(cats, checked, new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int item, boolean check) {
if(cats[item].equals("All Categories")) {
AlertDialog d = (AlertDialog) dialog;
ListView v = d.getListView();
int i = 0;
while(i < cats.length) {
v.setItemChecked(i, check);
checked[i] = check;
i++;
}
}
checked[item] = check;
}
});
Did you try replacing setMultiChoiceItems to setSingleChoiceItems in your dialog?

Categories

Resources