Question

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.

Was it helpful?

Solution

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?

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top