dividing values in spinners - Android

孤街浪徒 提交于 2019-12-24 20:41:12

问题


I am trying to get the values from spinner 1 and divide it with the value from spinner 2 and then multiply with the current amount. This is the code i have but it gives me a force close when i try and convert.

final EditText editCurr = (EditText) findViewById(R.id.etamount);
    Button convert = (Button) findViewById(R.id.btn_convert);
     convert.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v){
             double curr = Double.valueOf(editCurr.getText().toString());


                double result2 = Double.valueOf(spinner1.toString()) / Double.valueOf(spinner2.toString());
                double result = curr * result2;
                etResult.setText(String.valueOf(result));
         }
     });

to make it more clearer what i'm trying to do i have shown the xml of my array:

<string-array name="currencies">
    <item>EUR, Euro</item>
    <item>GBP, British Pound</item>
    <item>USD, US Dollar</item>
    </string-array>

<string-array name="currenciesvalues">
    <item>1</item>
 <item>2</item>
    <item>3</item>
</string-array>

currencies are the string that show on the spinners and currenciesvalues are numbers assigned to the string e.g EUR has a value of 1. in the method im trying to get the amount from curr and multiply by the value that occurs from dividing the value of spinner1 with spinner2 e.g. USD value 3 / GBP value 2

hope this makes it a little clearer


回答1:


Are you getting the value of the Spinner and assigning it to spinner1 and spinner2 somewhere in the code that you have not posted?

If you are not then that is where the problem is. You can't get the Spinner's value by just calling spinner1.toString() or spinner2.toString().

To get the value of the spinner use...

spinner.getSelectedItem().toString(); 

So in your case...

double result2 = Double.valueOf(spinner1.getSelectedItem().toString()) / Double.valueOf(spinner2.getSelectedItem().toString());



回答2:


I think this is the bug:

double result2 = Double.valueOf(spinner1.toString()) / Double.valueOf(spinner2.toString());

Change it to:

double result2 = Double.valueOf(spinner1.getSelectedItem().toString()) / Double.valueOf(spinner2.getSelectedItem().toString());


来源:https://stackoverflow.com/questions/17871238/dividing-values-in-spinners-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!