Alert dialog with multiple choice to be checked dynamically android - android

My code fetches data from server and made it to display in the alert dialog box with listview, multiple choice option but now, i want every data to be pre checked before loading into listview and mark checked if the condition satisfies is this possible in alert dialog.
//this is my code for loading the value into alertdialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select Category List");
final ListView modeList = new ListView(getActivity());
// Creating a button - Load More
Button btnDone = new Button(getActivity());
btnDone.setText("Done");
btnDone.setTextColor(getActivity().getResources().getColor( android.R.color.white));
btnDone.setBackgroundResource(R.drawable.logout_btn);
final ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_multiple_choice,
android.R.id.text1, EavesList);
modeList.addFooterView(btnDone);
modeList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
modeList.setAdapter(modeAdapter);
builder.setView(modeList);
My question: Is it possible to check the condition and mark checked before loading multiple choice in alert dialog. if possible, then please respective tutorial or any code will be helpful.

you can use
setItemChecked() method of ListView for the purpose.
you can use this, after
modeList.setAdapter(modeAdapter);
and put your condition here, and then setItemChecked(position, value); to set the item as checked! if it satisfies your condition.

Assuming your list is of type CharacterSequence[] or can be converted to one, you can use
AlertDialog.setMultiChoiceItems(CharacterSequence[] list, boolean[] checkedItems, OnMultiChoiceClickListener listener)
Pass the EavesList as a CharacterSequence[] as first parameter, a boolean[] specifying which list items are to be checked while creating the Dialog as the second and the listener for when the user toggles the items as the third parameter.

Related

ListView does not show changes until focus changes after notifyDataSetChanged

I have an AlertDialog with a ListView set to multiple selection on it. It also has a Button on it.
The Button open another AlertDialog that if ok'ed will remove the selected items from the data set of the ListView, and then tell the adapter of the list view that the dataset has changed with the notifyDataSetChanged() method.
This all works fine except for one thing. The ListView does not update it's content until I interact with something. Then it updates to the correct data.
This is not a big problem, but I really would like the ListView to appear correct at once, and not just after the focus has changed.
Code:
Button remove = (Button) view.findViewById(R.id.btn_remove_questions_edit_rack);
final Context con = this;
remove.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Builder warnBuild = new Builder(con);
warnBuild.setMessage(R.string.question_deletion_warning);
warnBuild.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
SparseBooleanArray checked = list.getCheckedItemPositions();
for (String s : keys)
{
int i = keys.indexOf(s);
if (checked.get(i))
{
toRemove.add(map.get(s));
map.remove(s);
}
}
keys.clear();
keys.addAll(map.keySet());
((ArrayAdapter) list.getAdapter()).notifyDataSetChanged();
list.clearChoices(); //This makes sure the selection is cleared, if it isn't, some of the other items (those that now has the index of the selected items) will be selected when the View refreshes.
dialog.dismiss();
}
});
//Negative button here, not relevant.
}
});
Where map and keys are:
final HashMap<String, QualityQuestion> map = new HashMap<>();
//I add items to the map
final ArrayList<String> keys = new ArrayList<>(map.keySet());
And toRemove is where I store the items to be removed from the actual object they are on when the ok button on the original AlertDialog is pressed.
This is how I populate my ListView in the first place:
final ListView list = (ListView) view.findViewById(R.id.list_questions_edit_rack);
list.setAdapter(
new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_1,
keys));
I have tried things like list.invalidateViews(), list.invalidate and other things I found in questions similar to mine here on SO. But none of that made any difference. I suspect my problem to be different from theirs since my items clearly are updated, it just takes a change of focus on the original AlertDialog for the change to be visible.
How can I make the ListView show the changes in it's data source imidiatly insted of after a focus change?
By calling
((ArrayAdapter) list.getAdapter()).notifyDataSetChanged();
you get a fresh adapter which is almost certainly not identical to the anonymous adapter you used to populate your list in the first instance.
See also the documentation for ListView.getAdapter()
Returns the adapter currently in use in this ListView.
The returned adapter might not be the same adapter passed to setAdapter(ListAdapter) but might be a WrapperListAdapter.
From the point of view of this fresh adapter, the data set hasn't changed because the changes happened way before it was instantiated.
To solve your problem, make your list and your list adapter members of your activity class (or the scope where you want to keep them alive):
private ArrayList<String> keys;
private ArrayAdapter myAdapter;
private ListView list;
Then in your "onCreate()"
keys = ...; // initialization of ArrayList with the needed data
myAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_1,
keys);
list = (ListView) view.findViewById(R.id.list_questions_edit_rack);
list.setAdapter(myAdapter);
This way, in your "OnClickListener" you can notify "myAdapter":
keys.addAll(map.keySet());
myAdapter.notifyDataSetChanged();
Hope this helps :)
You can tweak it, by granting focus to another view, and then requesting it back:
view.requestFocus();
You can also use:
view.requestFocusFromTouch();

Android Dialog setMultiChoiceItems - ArrayList

I want to create Dialog with multi choice items like on http://developer.android.com/guide/topics/ui/dialogs.html
The only problem is, that I'm getting ArrayList from MySQL database wih PHP, so i can't provide resource id, like it's requested. Any help is appreciated,
Thanks!
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("")
.setMultiChoiceItems(db.getProjetky(), null, //the first argument needs to be resource id (int)
new DialogInterface.OnMultiChoiceClickListener()
.......
db.getProjekty();
public ArrayList<String> getProjetky() {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", get_project_tag));
ArrayList<String> projekty = jsonParser.getProjektyArrayFromUrl(URL,params);
return projekty; //returns ArrayList<String>
}
You can use an array of strings, as written in the documentation:
public AlertDialog.Builder setMultiChoiceItems (CharSequence[] items,
boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener
listener)
Added in API level 1 Set a list of items to be displayed in the dialog
as the content, you will be notified of the selected item via the
supplied listener. The list will have a check mark displayed to the
right of the text for each checked item. Clicking on an item in the
list will not dismiss the dialog. Clicking on a button will dismiss
the dialog.

Getting checkbox values from ListView

I have a listview of that's tied to an array adapter. For the life of me I can't figure out how to get a list of the checked boxes in the listview.
CheckViewArrayAdapter adapter;
int[] intarray;
paramListView = (ListView) findViewById(R.id.datalog_paramselectlist);
// get all supported params
intarray = ConMan.Ecu.getSupportedParamArrayVals();
LinkedHashMap<Integer,String> hm = new LinkedHashMap<Integer,String>();
for( x=0;x<intarray.length;x++){
hm.put(intarray[x] , ConMan.Ecu.paramToText(intarray[x]));
}
adapter = new CheckViewArrayAdapter(this,android.R.layout.simple_list_item_multiple_choice , android.R.id.text1, hm);
adapter.setBoolArray(ConMan.Ecu.getSelectedParamFlagArray());
// Assign adapter to ListView
paramListView.setAdapter(adapter);
I have a setOnItemClickListener for paramListView that works, but I just want to get the final set of checked checkboxes when the screen exits. I simply don't know where to look.
I have a setOnItemClickListener for paramListView that works, but I just want to get the final set of checkboxes when the screen exits.
I assume that you are not setting the choice mode for your ListView. If you do use:
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
then in your onPause() method, you can ask for an index of the checked rows with ListView#getCheckedItemPosition() and you don't need to change the checked state manually in your OnItemClickListener.

Android: How to set the selection in a single choice AlertDialog?

I created a single choice AlertDialog with "Apply" and "Cancel" buttons. When the user presses "Cancel", I would like to set the selected item back to what it was when the dialog was first shown (I have the value stored already).
I know how to set the selected item when the dialog is first created in setSingleChoiceItems() but is there a way to set it again later?
I would like to be compatible with API level 7, so I'd rather not use onPrepareDialog().
Well, nobody could find a solution to my problem, so I settled for a dialog which doesn't use buttons. When the user presses an item in the list, that selection is applied and the dialog is dismissed. No need to remember previous choices or support cancelling.
You can create your dialog on the spot rather than going through showDialog and onCreateDialog. This way its always using the current selection we give to setSingleChoiceItems.
//where we display the dialog
showDialog(MYDIALOG);
AlertDialog.Builder builder = new Builder(this);
String[] choices = {"A","B","C"};
builder.setSingleChoiceItems(choices,current_choice,null);
builder.setPositiveButton("Select",null);
builder.setNegativeButton("Cancel",null);
builder.show();
...
protected Dialog onCreatDialog(int id) {
if (id==MYDIALOG) {
AlertDialog.Builder builder = new Builder(this);
String[] choices = {"A","B","C"};
builder.setSingleChoiceItems(choices,current_choice,null);
builder.setPositiveButton("Select",null);
builder.setNegativeButton("Cancel",null);
return builder.show();
}
return null;
}
In Altert Dialog For creating single choice have you used single choice list view or radio group?
If You have used Single Choice Listviwe then no need to worry.
IF you have used Radio Group then you have to keep track of selected Radio Button Using Global Varialbe in your activity.
What you want to do when user click on cancel.
when user click on cancel than do you want to remove selected item from list if yes then you have to do the following.
In Your listitemseleted listener
alb.setSingleChoiceItems(items, 0, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/* which argument is the position of the item in
array items you have to remove this item from items array
Make your items array global variable.since in java array are
immutable you have to use arraylist.Arraylist can be converted
to array.*/
}
});
hope this will help if any question feel free to ask.

Android: Alert Dialog with CheckedTextView

Ok guys..I have a problem...
I need to create a dialog with 3 CheckedTextView. And when i open a dialog, second item should be checked...How to do that ? Code ...
#Override
protected Dialog onCreateDialog (int id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Something..");
builder.setInverseBackgroundForced(true);
ListView listView = new ListView(this);
listView .setAdapter(new ArrayAdapter(Settings.this, android.R.layout.select_dialog_multichoice, new String {a ,b, c}));
builder.setView(listView );
http://developer.android.com/guide/topics/ui/dialogs.html
check adding check boxes and radio buttons ,
One method would be ,
Have a flag through which you can decide
which to check next time when you popup the dialog and set the radio button in code ,
get radio button view and use toggle()
Check radio buttons and checkbox,
http://developer.android.com/resources/tutorials/views/hello-formstuff.html
Another method would be to use CheckBoxPreference.
Hope it helps.
Try this listView.getAdapter().getItem(1);. if your 2nd list item is check box, then set it checked by setChecked(true);

Categories

Resources