Android Dialog setMultiChoiceItems - ArrayList - android

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.

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();

Alert dialog with multiple choice to be checked dynamically 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.

Android : Listview stuff

I have a listview displaying list of items and a button at the bottom. On click of button, i'am displaying one alert dailog box to take input from user and adding that input to the listview. 1. How can i make sure the new input/entry should add always at top of listview? (Right now it is adding at bottom always)2. Is it possible to position the list view at the new entry? (i.e if the new entry is added at top, the list should be positioned at the top)Please guide me.
Inside onCreate()...
list = (ListView)findViewById(R.id.planetList);
adapter = new ArrayAdapter<String>(MyListViewActivity.this,
R.layout.my_list_row, R.id.planetNameTextView);
for (int i = 0; i < planetNamesArray.length; i++) {
adapter.add(planetNamesArray[i]);
}
list.setAdapter(adapter);
After taking input from user ....
adapter.add(newPlanetNameEnteredByUser);
adapter.notifyDataSetChanged();
you can use listview.setStackFromBottom(false) to fill your listview from top.
this link may help you.
http://developer.android.com/reference/android/widget/AbsListView.html#setStackFromBottom%28boolean%29
Yes you can do that, have two List.
List<String> old = new ArrayList<String>(); // contains your list content
List<String> new = new ArrayList<String>();
Now, when you want to add new content to ListView then add it first to the new ArrayList,
new.add("new content");
new.addAll(old); // add all the old contents
new.setSelection(position_you_want);
adapter.notifyDataSetChanged();
Add the object in array list
ArrayList<String> List= new ArrayList<String>();
ListView ListName= (ListView)findViewById(R.id.playerdata);
with
List.add(index, "value");
public void add (int index, E object)
Since: API Level 1
Inserts the specified object into this ArrayList at the specified location. The object is inserted before any previous element at the specified location. If the location is equal to the size of this ArrayList, the object is added at the end.
Parameters
index the index at which to insert the object.
object the object to add.
Throws
IndexOutOfBoundsException when location < 0 || > size()
and set list adapter
ListName.setAdapter(new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1 , List));

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.

Redraw android spinner

I have an android spinner item, in which the lines are made up of a TextView and an ImageView (a star, to mark that the user has marked that particular item as a favourite). Now, when a user favourites an item, I want to make the star appear next to that item in the spinner list, so I want to redraw the spinner to show the updated images. How do I do this?
What I'm doing now is that I'm creating a whole new spinner, with the appropriate images. This makes my spinner set the selected item to the first item in the list, which is annoying - I want it to stay the same. I have tried
spinner.setSelection(selectedItem);
This works for ANY number other than the number I actually want (the position of the currently selected item), then it sets the selected spinner item to the first in the list again.
So: how can I redraw the list with the updated information without having to recreate the whole list, or alternatively, how can I recreate the list and still preserve the spinner item selection?
To clarify: here's what I'm doing
// Callback for "favourite"-button
star.setOnClickListener(new ImageButton.OnClickListener() {
#Override
public void onClick(View arg0) {
// Toggle favourite
getActiveSelection().setStarred(getActiveSelection().isStarred() ? false : true);
reloadText();
createSpinner();
}
});
private void createSpinner() {
spinner = ((Spinner)findViewById(R.id.spinner));
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map = new HashMap<String, Object>();
// Populate spinner item list
for(int i=0; i<N; i++) {
SpinnerItem item = getSpinnerItem(i);
map = new HashMap<String, Object>();
map.put("Name", item.getName());
map.put("Icon", (item.isStarred() ? "On" : "Off"));
list.add(map);
}
MySpinnerAdapter aspn = new MySpinnerAdapter(this, list,
R.layout.spinner, new String[] { "Name", "Icon" },
new int[] { R.id.spinnerrow, R.id.spinnerrowicon });
spinner.setAdapter(aspn);
spinner.setSelection(getActiveSelection().getSpinnerPosition());
}
You may just update spinner adapter - let it know which item is starred when user clicks on the star icon (star.setOnClickListener...). What I would do:
In adapter construction, you pass only list of "Name" fields, no need for icon (all not starred by default)
You add separate function to adapter to set starred item (setStarred(String name))
On initial call, invoke setStarred to set initial selection (if any)
in star.setOnClickListener implementation, call setStarred for starred item on adapter which you obtain as (MySpinnerAdapter)spinner.getAdapter()
Or just try:
spinner.setSelection(getActiveSelection().getSpinnerPosition(),true);
That worked for me to update the spinner...
You need to call notifyDataSetChanged() on your spinner adapter when your data has changed.

Categories

Resources