Spinner OnItemSelectedListener double select issue - android

I am experiencing a odd problem. My OnItemSelectedListener seems only works one time, i mean that it shows my test Toast at the first time when clicking the coresponding items, but it doesn't show the test Toast when i hit the same item at the second time.( it does work when clicking a different item at the second time) What is the problem? plz help me
partial code is here
//get task object from menu
taskListArr = new ArrayList<Task>();
taskListArr = getCurrentTasks(taskListArr);
myTask=new TaskListAdapter(this, 0, taskListArr);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, TaskModel.sorts);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sortSpinner.setAdapter(aa);
sortSpinner.setOnItemSelectedListener(this);
#SuppressWarnings("unchecked")
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if(arg2 == 0){
Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_SHORT).show();
Collections.sort(taskListArr);
taskListView.setAdapter(myTask);
}
if(arg2 == 1){
Toast.makeText(getApplicationContext(), "2", Toast.LENGTH_SHORT).show();
Collections.sort(taskListArr, new DateComparator());
taskListView.setAdapter(myTask);
}
if(arg2 == 2){
Toast.makeText(getApplicationContext(), "3", Toast.LENGTH_SHORT).show();
Collections.sort(taskListArr, new PriorityComparator());
taskListView.setAdapter(myTask);
}
position = arg2;
}
public void onNothingSelected(AdapterView<?> arg0) {
}

Check out spinner in android developers site http://developer.android.com/reference/android/widget/Spinner.html
A view that displays one child at a time and lets the user pick among them. The items in the Spinner come from the Adapter associated with this view.
It selects one child at a time. So Selecting the already selected child again will not invoke onItemSelected function.

i agree with user936414 answer he is right but if still you want that your toast come again then add a on touch listener on your spinner and in the ontouch event add this
line sortSpinner.setOnItemSelectedListener(this);
by this each time as you touch your spinner listener will get invoked again and you will get the on itemselected each time

Related

Toast displayed twice

I have two spinners in a fragment, one of the spinner will display toast message when an item is selected. The problem is the toast in the first if-else statement displayed twice. Once when open the fragment and the second time when the item selected.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.add, container, false);
//------------------------------unit Spinner adapter---------------------------------------//
Spinner spinner = (Spinner) mRootView.findViewById(R.id.units);
//Create ArrayAdapter using string array and default spinner
ArrayAdapter<CharSequence> sAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.units, android.R.layout.simple_spinner_dropdown_item);
//Specify layout to use when list of choices appears
sAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Apply adapter to the spinner
spinner.setAdapter(sAdapter);
//----------------------------reminder Spinner adapter-------------------------------------//
Spinner reminderSpinner = (Spinner) mRootView.findViewById(R.id.list_reminder);
ArrayAdapter<CharSequence> reminderAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.countdown_reminder, android.R.layout.simple_spinner_dropdown_item);
reminderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
reminderSpinner.setAdapter(reminderAdapter);
spinner.setOnItemSelectedListener(spinnerListener);
reminderSpinner.setOnItemSelectedListener(spinnerListener);
return mRootView;
}
//---------------------------------Spinner Listener----------------------------------------//
AdapterView.OnItemSelectedListener spinnerListener = new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()) {
case R.id.units:
String selectedUnit = parent.getItemAtPosition(position).toString();
break;
case R.id.list_reminder:
String reminder = parent.getItemAtPosition(position).toString();
if (reminder.equals("24 hours")) {
Toast.makeText(getActivity(), "Reminder has been set 24 hours from the selected date", Toast.LENGTH_LONG).show();
} else if (reminder.equals("2 days")) {
Toast.makeText(getActivity(), "Reminder has been set 2 days from the selected date", Toast.LENGTH_LONG).show();
} else if (reminder.equals("3 days")) {
Toast.makeText(getActivity(), "Reminder has been set 3 days from the selected date", Toast.LENGTH_LONG).show();
} else if (reminder.equals("1 week")) {
Toast.makeText(getActivity(), "Reminder has been set 1 week from the selected date", Toast.LENGTH_LONG).show();
} else if (reminder.equals("2 weeks")) {
Toast.makeText(getActivity(), "Reminder has been set 2 weeks from the selected date", Toast.LENGTH_LONG).show();
} else if (reminder.equals("1 month")) {
Toast.makeText(getActivity(), "Reminder has been set 1 month from the selected date", Toast.LENGTH_LONG).show();
}
break;
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
};
//------------------------------------end spinner code-------------------------------------//
The '24 hours' toast displayed when user open the fragment and when the '24 hours' selected. I can't figure out what's wrong with the code. Help please?!
Your onItemSelectedListener might be getting called when you set it in onCreateView or it could be getting called when it initially displays the view. One hacky work-around is just to have a boolean that only executes the code in your listener after it has been called at least once before.
IIRC, a spinner must have a selected item no matter what, so it sets the first item when it launches and thus OnItemSelected is fired when the spinner starts up. No way around it unless you want to hack the spinner code.
What you could do is add a counter variable to determine whether or not it is the first time through and not display the toast if it is the first time.
This is because your adpater's onItemSelected is getting called when you are setting the adapter to your spinner. Add a debug point in that if block. A soluion would be to use a boolean flag to check whether the user has selected the spinner or not. Initially make it false. then before your switch check if that flag is false. If it is false then don't perform switch else do it. make the boolean flag true after the switch case. Hence it will be false for the first load and the toast will not appear for when the fragment is loaded.

Spinner OnItemSelectedListener() not working with one item in list.

So I am having a problem with a spinner not firing the listener when there is only one item in the list.
Here is a break down of what i am trying to do: have a spinner with a string that displays an id/title for an object, there is a button to add items to this spinner that creates a dialog and returns and object from the dialog and updates the spinner. I currently have the spinner working to add items to the spinner after the dialog closes. the code works as intended when there are multiple items in the spinner, however if there is only one item in the spinner then no onitemselectedlistener is fired. I know this because i have debugged the code and walked over the listener, when trying to select an item when there is only one item in the list does nothing. However, if i add another item to this list i am able to select it but only after first selecting the second or third so on item in the list
it is almost as if this item is if this is the item the spinner is currently selecting and therefore not generating any event for pressing it. I suppose my question would be how do i clear the spinner selection so that there is no Current selection. or would i have to do something like always have an entry in the spinner that says "Choose One" and have a check that would only do some action if the spinner's current selection wasn't equivalent to "Choose One".
my listener as it currently stands
methodSpin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(first == false) {
body.setText("");
currentMethod = hold.get(position);
Toast.makeText(methodActivity.this, "Text!" + position + ":" + currentMethod.body, Toast.LENGTH_SHORT).show();// for feedback/testing purposes
body.setEnabled(true);
body.setText(currentMethod.body);
}
else
Toast.makeText(methodActivity.this, "check == false", Toast.LENGTH_SHORT).show(); // for feedback/testing purposes
}
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(methodActivity.this, "onNothingSelected", Toast.LENGTH_SHORT).show();// for feedback/testing purposes
}
});
The Spinner will always have a selected item even if you call Spinner.setSelection( -1 ). I guess what you can do it to add a prompt
as the first option.
ArrayList<String> aOptions = new ArrayList<String>();
aOptions.add("Choose One");
aOptions.add("Option 1");
ArrayAdapter<String> adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_dropdown_item, aOptions);
Spinner spinner = (Spinner)findViewById(R.id.spinner);
spinner.setAdapter(adapter);

Compare Strings in List View in android

I am developing an Android app in which there are two list views. When user clicks on items of first list view that must be added to second list view. This is I have implemented correctly. But my problem is strings must not be repeated in second list view. Means if String A is there in list view 1 and I click on it, it moves to list view 2 and if again I click on String A, it should prompt message(Message will be handled by me). Here is my code. What am I missing?
ArrayList<String> arr2;
ArrayAdapter<String> adapter2;
arr2 = new ArrayList<String>();
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String selected = lv1.getItemAtPosition(arg2).toString();
arr2.add(selected);
adapter2 = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, arr2);
lv2.setAdapter(adapter2);
adapter2.notifyDataSetChanged();
}
});
probably this will work.
String selected = lv1.getItemAtPosition(arg2).toString();
if (!arr2.contains(selected)) {
//add item in second ListView
arr2.add(selected);
} else {
show popup
}
Finally, got it....
if (!arr2.contains(selected)) {
arr2.add(selected);
adapter2 = new ArrayAdapter < String > (getBaseContext(), android.R.layout.simple_list_item_1, arr2);
lv2.setAdapter(adapter2);
adapter2.notifyDataSetChanged();
} else {
Toast.makeText(getBaseContext(), "Already Contains", 1000).show();
}
I would suggest you save an ArrayList (your arr2) and check if arr2 already contains the string selected.
if(arr2.contains(selected)){
//continue with something else
}else{
//add to list and refresh Fragment
}
Use Contains method and check whether particular value exists in arr2 if it returns false then only perform arr.add(selected)
Change this
arr2.add(selected);
To
if(!arr2.contains(selected)){
arr2.add(selected);
}

Why is onNothingSelected method needed in spinner listener?

native English speaker, so I'd say sorry about my bad English skills to you guys.
I've been studing Android since 5 weeks ago. I tried to implement a spinner and my mentor asked why the onNothingSelected method is needed. I had nothing to say.
So, why do I need that method?? Can you reply it?
Following code is my spinner. It does correctly what I intended.
public class SpinnerViewPractice extends Activity {
private Spinner spinner;
private String spinner_value = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.spinnerviewpractice);
spinner = (Spinner)findViewById(R.id.spinner1);
String[] str = {"","good", "dislike", "like", "hate", "moderate"};
spinner.setPrompt("Set Text");
ArrayAdapter<String> list = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, str);
spinner.setAdapter(list);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
TextView tv = (TextView)arg1;
spinner_value = tv.getText().toString();
if(spinner_value.length() == 0)
{
spinner_value = "Nothing";
}
Toast.makeText(SpinnerViewPractice.this, spinner_value, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
Toast.makeText(SpinnerViewPractice.this, "NothingSelected", Toast.LENGTH_SHORT).show();
}
});
}
}
As the documentation describes:
Callback method to be invoked when the selection disappears from this view. The selection can disappear for instance when touch is activated or when the adapter becomes empty.
This means that the method is called whenever the currently selected item is removed from the list of available items. As the doc describes, this can occur under different circumstances, but generally if the adapter is modified such that the currently selected item is no longer available then the method will be called.
This method may be used so that you can set which item will be selected given that the previous item is no longer available. This is instead of letting the spinner automatically select the next item in the list.
From the doc here.
onNothingSelected is a Callback method to be invoked when the selection disappears from this
view. The selection can disappear for instance when touch is activated
or when the adapter becomes empty.
I think it pretty much answers your question. So if your spinner disappear for other reason except selecting the item then onNothingSelected will be called. So as it's name tells it is needed to find out when nothing is selected

pass previous index to spinner's onItemSelectedListener

I am using a spinner in my application. After selecting an index in spinner I open
a new activity and then come back to the first. Now my spinner is showing the previous selected value and if I select the same index again nothing happens.
The doc says onItemSelectedListener invokes iff the index is different from the previous. And I can't set it to default(0) when i come back.
So is there any alternative solution to do this? Please help me. Thanks. Here is my code:
companyspin.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onNothingSelected(AdapterView<?> arg0) {
}
public void onItemSelected(AdapterView<?> arg0,
android.view.View arg1, int arg2, long arg3) {
Object o = companyspin.getSelectedItem();
network = CheckNetworkStateReceiver.isOnline(context);
selectCompany = o.toString().trim();
Data.homeCommunityValue = arg2;
setCompanyList(arg2);
flagCatageory = false;
try {
tracker.trackEvent("Home", // Category
"Drop Down Selection", // Action
selectCompany, // Label
arg2); // Value
} catch (Exception e) {
e.printStackTrace();
}
}
});``
You start the new activity as soon as it's selected in the spinner ?
Just grab the data from the spinner you need for your activity in the onItemSele.... listener.
Set
mySpinner.setSelection(your_position)
before your new activity starts. If you want it to stay the on the same value in the spinner, a Button to activate your selection seems easier, and less error-prone for the user depending on what the selection do.
EDIT:
The selection is still the same afterwards so the callback will never fire. You can put a placebo object at position(0) with some info text "Choose here..." which you can return to after a valid selection, with setSelection. Just add a check in the listener if it's a valid choice or the placebo.
Since you want 1st item to be selected when you return to your main activity, you can try
companyspin.setSelection(0);
in onCreate() of main activity.

Categories

Resources