how to know if user clicked spinner android - android

I have implemented multiple(seven) spinners and populated them with three options: Yes, No, and Unknown. And "Unknown" is the default option. Now I want to know whether user clicked spinner or not. Since the default option can also be a valid answer, I could not work with getSelectedItemPosition() in Spinner class.
All I want to know is whether user clicked that particular spinner or not, so that I can generate alert message depending on this Info.

The first thing you should do is read the Spinners guide on the Android developer site. Having done that, you'll find this handy example:
public class MySpinnerActivity extends Activity implements OnItemSelectedListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}

Simpy,
First Set OnItemSelectedListener to each Spinner and then check in method,
if you have more spinner then getSelectedItem() using below code inside onItemSeleted Method,
String str1= (String) spinner1.getSelectedItem().toString();
String str2= (String) spinner2.getSelectedItem().toString();

Related

Get last selected Spinner value before change

I have a spinner and I want to get the last selected value of it when I click on the spinner (basically just before the items in the list are being shown).
How can I achieve this?
Update:
Example: There are a dynamic amount of spinners. User clicks in spinner 1 and selects a value, let's say "house". Then clicks somewhere else. Then clicks in spinner 1 again. What I now need is to return the value "house" that was previously was selected before the user selects a different value i.e. "car" in that spinner. I can not use the local storage to save that value beforehand because it's going to be a dynamic amount of spinners to be added.
And yes, I did in fact read the documentation at http://developer.android.com/guide/topics/ui/controls/spinner.html already but what I need isn't explained there.
Maybe you can declare a String array and then use it to storage the items values. Showing this in a TextView is a way to see if it works.
Something like this:
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
selection.setText(items[arg2]);
}
I already have faced a similar situation, but I don't remember exactly how I solved it. Tell me if it gives a better idea to you, I'm new participating here.
Spinner mySpinner=(Spinner) findViewById(R.id.your_spinner);
String text = mySpinner.getSelectedItem().toString();
When the user selects an item from the drop-down, the Spinner object
receives an on-item-selected event.
To define the selection event handler for a spinner, implement the
AdapterView.OnItemSelectedListener interface and the corresponding
onItemSelected() callback method. For example, here's an
implementation of the interface in an Activity:
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
...
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
The AdapterView.OnItemSelectedListener requires the onItemSelected()
and onNothingSelected() callback methods.
Then you need to specify the interface implementation by calling
setOnItemSelectedListener():
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
IN YOUR CASE:
TO se if the user clicked on the spinner, do this:
if (spin.getSelectedItemPosition() < 0) {
Spinner mySpinner=(Spinner) findViewById(R.id.your_spinner);
String text = mySpinner.getSelectedItem().toString();
}
This means user clicked the spinner, but not any items of it.
EDIT AGAIN
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
> ...
>
> public void onItemSelected(AdapterView<?> parent, View view,
> int pos, long id) {
> parent.getItemAtPosition(pos) //THIS GETS YOU THAT VALUE THAT THE USER CLICKED ON DYNAMICALLY
> }
>
> public void onNothingSelected(AdapterView<?> parent) {
> // Another interface callback
> }
> }
http://developer.android.com/guide/topics/ui/controls/spinner.html
Solution is to add a TextView widget with each added Spinner. Set the TextView to "gone" (not visible). When the spinner changes set the value to that TextView. This way you can store the last selected spinner value in the TextView. When the user clicks on the spinner and changes the value you can still access the previously selected/unselected value from the spinner through the TextView widget.
// Use this TextView to temporarily store the spinner value
final TextView hiddenTextView = new TextView(getContext());
hiddenTextView.setVisibility(View.GONE);
final Spinner spinner = new Spinner(getContext());
spinner.setPrompt(getString(R.string.email_other));
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(), R.array.email_types, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
Log.d(TAG, "TextView Value before spinner change: " + hiddenTextView.getText());
String spinnerValue = String.valueOf(spinner.getSelectedItem());
hiddenTextView.setText(spinnerValue);
Log.d(TAG, "TextView Value after spinner change: " + hiddenTextView.getText());
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
return;
}
});

ListView Selected position with setTextFilterEnabled

I have the following code that starts a listview with 100 options. Also it activates the software keyboard, for easy-searching of the options. If i choose an option, the position of the selected option stores in the string array items[]. The problem is that when i search an option by keyword, select it and then go back, it points at the current position not at the current value.
How to prevent this?
public class MyListActivity extends ListActivity {
String[] items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
ListView lView = getListView();
lView.setChoiceMode(2);
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
lView.setTextFilterEnabled(true);
items = getResources().getStringArray(R.array.items1);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_checked, items));
}
public void onListItemClick(ListView lv, View v, int position, long id) {
lv.setItemChecked(position, lv.isItemChecked(position));
String selectedValue = (String) getListAdapter().getItem(position);
Toast.makeText(this, selectedValue, Toast.LENGTH_SHORT).show();
}
}
I think that you should create your own custom Adapter , and then in that adapter just simply override the getItem(int position) function to return the value that you need. If u haven't done it before then check out for instance this tutorial
As it turns out, having a filterable adapter doesn't play well with any choice mode (single or multiple). The only solution to this is to manually maintain the state of the selected items (a set or a list of strings in your case), and then simply loop through it every time you change the filter, in order to select the items you need. This has already been described in great detail here: Multiple Choice Searchable ListView
You obviously can't use the setTextFilterEnabled() method for this, you simply need to add an EditText in your layout and then set a TextWatcher on that in order to get all the necessary callbacks.

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

How do I read the string from a Spinner selected event

I have a simple app where the user selects one of the US states and the state selected is to be used to list all of the counties in that state. In onCreate, I built an arrayadapter called Stateadapter, and set it to the spinner object "spinState". I then initialized a listener class StateOnItemSelectedListener. Outside of onCreate, I have the StateOnItemSelectedListener class that will read which State was selected in the spinner, and then perform the rest of the app's tasks.
I have two problems: when single stepping thru the code in debug mode, the "parent.getItemAtPosition(pos).toString" does not return the string value of the selected state (though numerous web examples suggest this should work).
Second, when running, the app fires the listener when going thru onCreate and all appears well until the user selects the spinner on the ui, and the app then does a force close.
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinState = (Spinner)this.findViewById(R.id.spinState);
ArrayAdapter<String> Stateadapter = new ArrayAdapter<String> (this,android.R.layout.simple_spinner_item, array_spinState);
Stateadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinState.setAdapter(Stateadapter);
spinState.setOnItemSelectedListener(new StateOnItemSelectedListener());
}
public class StateOnItemSelectedListener implements OnItemSelectedListener
{
public void onItemSelected(AdapterView<?> parent, View itemSelected, int pos, long id)
{ State = spinState.getItemAtPosition(pos).toString();
//Do Stuff base on State;
}
public void onNothingSelected(AdapterView<?> parent)
{ //Do nothing here
}
}
Try doing what they do in the Spinner Tutorial, they create the adapter in a different way, but eventually they use the same code to access to selected item and it works.
What is the error in log cat from the force close, and what getItemAtPosition does return?

Spinner OnclickListener event executes twice, how to handle both events

Spinner OnclickListener event executes twice -
Spinner initialization
User selected manually
where as implementation of listener is as :
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
Problem definition
I want to save user selected text into data storage, when user choose any item from spinner, and I am able to do this. But my another task is that to show previously selected item (access from data storage) as selected item in spinner, but each time when I call spinner's activity, spinner shows first item as default selected item, and also in data storage it make change previous item to default.
How can I make difference between 'Spinner initialization' and 'User selected manually' events?
You have to handle both events logically. As these references (Android Spinner selection, problem on spinner) says that you have to use flag variable to handle this, I am putting a code sample.
Hope this will help you to clear your logic.
public class TestActivity extends Activity {
//Checks report spinner selection is default or user selected item
private boolean isDefaultSelection;
//Spinner setup
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
// Set true at onCreate
isDefaultSelection = true;
spinner = (Spinner) findViewById(R.id.id_of_spinner);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String> (this, R.layout.drop_down_custom_row, data);
//Implement custom view for drop down of spinner
//spinnerAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(isDefaultSelection) { //If spinner initializes
spinner.setSelection("Set_here_id_of_data_item_from_storage_which_was_previously_stored");
isDefaultSelection = false;
} else { //If user manually select item
int itemPosition = spinner.getSelectedItemPosition();
//Write here code to store selection (itemPosition) of user into data storage
}
}
public void onNothingSelected(AdapterView<?> parent) {
//User selected same item. Nothing to do.
}
});
}
}
Hope it will clear your doubt.
You can call the setSelection at the same time that the items are added to the adapter, see this example: How to avoid onItemSelected to be called twice in Spinners

Categories

Resources