0

I am making a currency converter with two spinners. I want to make an "if" function using the values of the spinner's selected item like below.

@Override
public void onClick(View v) {
    if (spinner1.getSelectedItem()=="Dollars" && spinner2.getSelectedItem()=="Euros") {
        convertDollarstoEuros();
    }
    if (spinner1.getSelectedItem()=="Euros" && spinner2.getSelectedItem()=="Euros") {
        convertEurostoEuros();
    }
Toast.makeText(MainActivity.this,
        "OnClickListener : " + 
                "\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) + 
                "\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()),
            Toast.LENGTH_SHORT).show();
    }

The problem is that the toast is showing, but the currencies aren't converting. The toast part is working, but the spinner part isn't. Any help would be greatly appreciated. Here is my LogCat:

http://oi39.tinypic.com/2n7i63o.jpg

Raman
  • 1,507
  • 3
  • 15
  • 25
Rohodude
  • 495
  • 2
  • 5
  • 18

2 Answers2

1

Use the OnItemSelectedListener on your Spinner

spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {

            String text = spinner1.getSelectedItem().toString().trim();
            if (text.equalsIgnoreCase("Dollars")) {

                //do something
                            }

        }

        public void onNothingSelected(AdapterView<?> arg0) {

        }
    });
Srikanth Pai
  • 926
  • 3
  • 17
  • 30
  • The problem is that I have to get the position of both of the spinners. Isn't this the listener for only one spinner? What should I do? – Rohodude Jun 16 '13 at 02:29
  • firstly, why do you need two spinners? A spinner is similar to a combo box where you select a item from the dropdown and do something for that – Srikanth Pai Jun 16 '13 at 02:30
0

You are comparing String directly. In Java, you should be comparing Strings with the equals method.

if("Dollars".equals(spinner1.getSelectedItem()) && ...

See the following question for more detail: How do I compare strings in Java?

Community
  • 1
  • 1
Jay Lindquist
  • 429
  • 2
  • 5