I got a Spinner in my app and it does not work when an item is clicked. I get the values but the if condition is not getting worked.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object item = parent.getItemAtPosition(pos);
String Text = effecttwo.getSelectedItem().toString();
System.out.println("spinner is -"+item+"-");
// I get the correct values in System.out.println
if(Text=="Hue"){
// not entering into this condition or any other condition
}else if(Text=="Saturation"){
}else if(Text=="Brightness"){
}else{
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
Please suggest me what I am doing wrong.
I get the values but the if condition is not getting worked.
if(Text=="Hue"){
Wrong
use .equals or .equalsIgnoreCase to compare strings
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equals(java.lang.Object)
if(Text.equals("Hue"))
{
}
What is the difference between == vs equals() in Java?
You dont compare string with ==. Use this:
if(text.equals("Hue"))
{
}
So your code goes this way:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object item = parent.getItemAtPosition(pos);
String Text = effecttwo.getSelectedItem().toString();
System.out.println("spinner is -"+item+"-");
// I get the correct values in System.out.println
if(text.equals("Hue")){
// not entering into this condition or any other condition
}else if(text.equals("Saturation")){
}else if(text.equals("Brightness")){
}else{
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
Don't do the listener inside anonymous class.
Do it withspinner.setOnItemSelectedListener(this) and put implement AdapterView.OnItemSelectedListener after your fragment or activity.
Related
i create in a two way data binding spinner in Android, and added value into with a result of a REST GET.
I need now to add the first value of the spinner as an empty string that when it will be selected from the spinner, the value will be null.
In the fragment class i wrote this code:
//spinner
appCompatSpinner = binding.spinner;
spinnerAdapter = new SpinnerAdapter(getActivity(), viewModel.usersDetailsList );
appCompatSpinner.setAdapter(spinnerActorAdapter);
appCompatSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
viewModel.onSelected(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
mAdapter.notifyDataSetChanged();
Can someone please help me to achieve that?
As a continuation of the question here, I found that the listener of the spinner is never executed (or) triggered and I am not able to solve the issue.
Here is the part of the code with the spinner and the listener:
Spinner priority = (Spinner)findViewById(R.id.priority);
priority.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d("listener","it works");
Log.d("value",""+parent.getSelectedItem().toString().equalsIgnoreCase("Low"));
/*if(parent.getSelectedItem().toString().equalsIgnoreCase("Low"))
imageId = R.drawable.blue;
else if(parent.getSelectedItem().toString().equalsIgnoreCase("Medium"))
imageId = R.drawable.green;
else
imageId = R.drawable.red;*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
In the log, the values of listener and value are not printed at all.
Modified code.
Spinner priority = (Spinner)findViewById(R.id.priority);
priority.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d("listener","it works");
//Instead of doing parent.getSelectedItem(), get the adapter from parent and from that adapter get item at position as below.
Log.d("value",""+parent.getAdapter().getItem(position).toString().equalsIgnoreCase("Low"));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
If your data is string then it will work else you are passing any custom object then you need to cast result from this parent.getAdapter().getItem(position) to that custom object class.
Finally found the solution :
String priortyStr = priority.getSelectedItem().toString();
int imageId = 0;
if(priortyStr.equals("Low"))
imageId = R.drawable.blue;
else if(priortyStr.equals("Medium"))
imageId = R.drawable.green;
else
imageId = R.drawable.red;
I am working on my first ever android app, and I'm creating basic exercise/calorie counter. I have two spinners, one for the selected type of exercise, and one for the time spent preforming said exercise in minutes. I need to be able to check the value/position of both spinners so I can do something like this:
PSUEDO CODE:
if(Exercise spinner = "push-ups")
{
CaloriesBurned = TimeSpinnerValue*450
}
if(Exercise spinner = "sit-up")
{
CaloriesBurned = TimeSpinnerValue*350
}
etc . . . nothing fancy. My spinners are populated from a String Array in my String.xml. But I dont know how get the value of the spinner so I can use it in some IF statements in my java code.
use like this for compair any string with your spinner.
spinner.equals("push-ups");
You need to implement OnItemSelectedListener for getting the selected value from the Spinner. Then override,
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
int id = parent.getId();
switch (id) {
case R.id.first_spinner:
// your stuff here
break;
case R.id.second_spinner:
// your stuff here
break;
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
yourSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int position, long arg3) {
String selectedString = (String) (yourSpinner.getAdapter()).getItem(position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}});
check this link fro more info
Generically, you'll want to follow this pattern:
SpinnerAdapter adapter = Spinner.getAdapter();
int position = Spinner.getSelectedItemPosition();
Object value = adapter.getItem(position);
Since you are loading it with String values, you can then cast value to a String.
Have some field in your activity to hold value of spinner, initialize with some defaultvalue
implement onItemSelectedListener on spinners, and in onItemSelected get value of selected item, by position argument of onItemSelected(AdapterView adapterView, View view, int position, long id)
I have a spinner in my Android app, and its onItemSelected() event automatically gets triggered upon entering the activity.
How do I avoid this?
We can use a flag, and just enable it when the spinner is really touched.
private boolean isSpinnerTouched = false;
spinner.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
isSpinnerTouched = true;
return false;
}
});
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View arg1,
int arg2, long arg3) {
if (!isSpinnerTouched) return;
// do what you want
}
});
To add on Jerry Abraham, You should clear selection before enabling setOnItemSelectedListener
Spinner mSpinner=(Spinner)findViewById(R.id.mySpinner);
int initialSelectedPosition=mSpinner.getSelectedItemPosition();
mSpinner.setSelection(initialSelectedPosition, false); //clear selection
mSpinner.setOnItemSelectedListener(this); //set listener after clearing section
I have solved this issue,
You can avoid this issue by not setting any default values to the spinner
int initialposition=spinner.getSelectedItemPosition();
spinner.setSelection(initialposition, false);
This will avoid entering into onItemSelected()
There are no any way to avoid this.
You may add some flag, indicating readiness of your application and use it in your onItemSelected() method to decide, what to do in each case.
Well, you can add a dummy selection to the initial adapter, and ignore position number in the setOnItemSelectedListener. It's not pretty but it works. See this code for setting up the items for an array adapter.
List<String> names = new ArrayList<String>();
names.add("");
names.addAll(realValues);
Then in your setOnItemSelectedListener you can do this:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
if (position > 0)
{
String name = names.get(position - 1);
}
else
{
Log.d(TAG, "selected nothing or perhaps the dummy value");
}
}
I have found a solution for this problem and posted it here (with code sample):
Spinner onItemSelected() executes when it is not suppose to
Simple and easy is this...
validate with a boolean to see if is first time...
Spinner mySpinner = (Spinner)findViewById(R.id.spinner_xml_pro);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(isSpinnerInitial){ // globar var boolean isSpinnerInitial = false;
//do something
}else
isSpinnerInitial=true;
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Check this with spinner.post(new Runnable()...)
or this other my source
I think that you can use spinner position which is a better approach in my opinion.
Create a global variable where you store the spinner position, in onItemSelected method the position is provided you can compare them, if they are the same do not make an action.
private int spinnerPosition; \\ Global variable
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
if(spinnerPosition != position){
// Do whatever you like
// Do not forget to save the new position
spinnerPosition = position;
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
You can avoid it by ignoring the first click by,
private boolean isSpinnerInitial = true; //As global variable
public void onItemSelected(xxx xxx, xxx xxx, xxx xxx, xxx xxx) {
if(isSpinnerInitial) {
isSpinnerInitial = false;
return;
}
// Write your code here
}
How can you set the event listener for a Spinner when the selected item changes?
Basically what I am trying to do is something similar to this:
spinner1.onSelectionChange = handleSelectionChange;
void handleSelectionChange(Object sender){
//handle event
}
Some of the previous answers are not correct. They work for other widgets and views, but the documentation for the Spinner widget clearly states:
A spinner does not support item click
events. Calling this method will raise
an exception.
Better use OnItemSelectedListener() instead:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
This works for me.
Note that onItemSelected method is also invoked when the view is being build, so you can consider putting it inside onCreate() method call.
Spinner spnLocale = (Spinner)findViewById(R.id.spnLocale);
spnLocale.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// Your code here
}
public void onNothingSelected(AdapterView<?> adapterView) {
return;
}
});
Note: Remember one thing.
Spinner OnItemSelectedListener event will execute twice:
Spinner initialization
User selected manually
Try to differentiate those two by using flag variable.
You can implement AdapterView.OnItemSelectedListener class in your Activity.
And then use the below line within onCreate()
Spinner spin = (Spinner) findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);
Then override these two methods:
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
selection.setText(items[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
selection.setText("");
}
https://stackoverflow.com/q/1714426/811625
You can avoid the OnItemSelectedListener() being called with a simple check: Store the current selection index in an integer variable and check within the onItemSelected(..) before doing anything.
E.g:
Spinner spnLocale;
spnLocale = (Spinner)findViewById(R.id.spnLocale);
int iCurrentSelection = spnLocale.getSelectedItemPosition();
spnLocale.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (iCurrentSelection != i){
// Your code here
}
iCurrentSelection = i;
}
public void onNothingSelected(AdapterView<?> adapterView) {
return;
}
});
Of cause the iCurrentSelection should be in object scope for this to work!
It doesn't matter will you set OnItemSelectedListener in onCreate or onStart - it will still be called during of Activity creation or start (respectively).
So we can set it in onCreate (and NOT in onStart!).
Just add a flag to figure out first initialisation:
private Spinner mSpinner;
private boolean mSpinnerInitialized;
then in onCreate (or onCreateView) just:
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (!mSpinnerInitialized) {
mSpinnerInitialized = true;
return;
}
// do stuff
}
public void onNothingSelected(AdapterView<?> adapterView) {
return;
}
});
Find your spinner name and find id then implement this method.
spinnername.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
The docs for the spinner-widget says
A spinner does not support item click events.
You should use setOnItemSelectedListener to handle your problem.
For kotlin you can use:
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
}
override fun onNothingSelected(p0: AdapterView<*>?) {
}
}
Note: for parameters of onItemSelected method I use custom variable names
spinner1.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
//add some code here
}
);
take a global variable for current selection of spinner:
int currentItem = 0;
spinner_counter = (Spinner)findViewById(R.id.spinner_counter);
String[] value={"20","40","60","80","100","All"};
aa=new ArrayAdapter<String>(this,R.layout.spinner_item_profile,value);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_counter.setAdapter(aa);
spinner_counter.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(currentItem == position){
return; //do nothing
}
else
{
TextView spinner_item_text = (TextView) view;
//write your code here
}
currentItem = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//R.layout.spinner_item_profile
<?xml version="1.0" encoding="utf-8"?>
<TextView android:id="#+id/spinner_item_text"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/border_close_profile"
android:gravity="start"
android:textColor="#color/black"
android:paddingLeft="5dip"
android:paddingStart="5dip"
android:paddingTop="12dip"
android:paddingBottom="12dip"
/>
//drawable/border_close_profile
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#e2e3d7" />
</shape>
</item>
<item android:left="1dp"
android:right="1dp"
android:top="1dp"
android:bottom="1dp">
<shape android:shape="rectangle">
<solid android:color="#color/white_text" />
</shape>
</item>
</layer-list>
If you want a true onChangedListener(). Store the initial value in the handler and check to see if it has changed. It is simple and does not require a global variable. Works if you have more than one spinner on the page.
String initialValue = // get from Database or your object
mySpinner.setOnItemSelectedListener(new SpinnerSelectedListener(initialValue));
...
protected class SpinnerSelectedListener implements AdapterView.OnItemSelectedListener {
private SpinnerSelectedListener() {
super();
}
public SpinnerSelectedListener(String initialValue) {
this();
this.initialValue = initialValue;
}
private String initialValue;
// getter and setter removed.
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
final String newValue = (String) spinHeight.getItemAtPosition(position);
if (newValue.equals(initialValue) == false) {
// Add your code here. The spinner has changed value.
// Maybe useful.
// initialValue = newValue;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Maybe useful.
// initialValue = null;
}
}
Objects are your friend, use them.
spinner.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
//add some code here
}
);
This will work
intialize the spinner and findviewbyid and use this it will work
Spinner schemeStatusSpinner;
schemeStatusSpinner = (Spinner) dialog.findViewById(R.id.spinner);
schemeStatusSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
if(schemeStatusSpinner.getSelectedItemId()==4){
reasonll.setVisibility(View.VISIBLE);
}
else {
reasonll.setVisibility(View.GONE);
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
By default, you will get the first item of the spinner array through
value = spinner.getSelectedItem().toString();
whenever you selected the value in the spinner this will give you the selected value
if you want the position of the selected item then do it like that
pos = spinner.getSelectedItemPosition();
the above two answers are for without applying listener
The best way what I think would be to have an flagitemselected = 0; in onCreate(). And on item selected event increment that flag i.e flagitemselected++; and then check
if(flagitemselected!=1)
{
// do your work here
}
This will help I guess.
I know this was long solved but I have a "Please select" string at the top of my string arrays. Then when you write the listener
yourspinner.onItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(adapterView: AdapterView<*>?, view: View, i: Int, l: Long) {
yourvalue = yourspinner.getSelectedItem().toString()
when(yourvalue){
"Please Select" -> // DO nothing
else -> // Do something
}
}
override fun onNothingSelected(adapterView: AdapterView<*>?) {
return
}
}
You can of course extend the when statement to have different responses or actions.
One trick I found was putting your setOnItemSelectedListeners in onWindowFocusChanged instead of onCreate. I haven't found any bad side-effects to doing it this way, yet. Basically, set up the listeners after the window gets drawn. I'm not sure how often onWindowFocusChanged runs, but it's easy enough to create yourself a lock variable if you are finding it running too often.
I think Android might be using a message-based processing system, and if you put it all in onCreate, you may run into situations where the spinner gets populated after it gets drawn. So, your listener will fire off after you set the item location. This is an educated guess, of course, but feel free to correct me on this.