我现在只需要一点帮助。该应用程序运行良好,但当你输入前。美元,2到SEK它的结果是13,38。但如果我将金额改为3则没有任何反应。我必须来回改变电流才能做出改变。我希望应用程序在更改值后立即更改结果。请帮忙!:)
package com.example.currencyconverter;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity {
private String [] currency_name;
private ArrayAdapter<String> adapter;
private Spinner spin1, spin2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpTheSpinners();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
private void setUpTheSpinners() {
currency_name = getResources().getStringArray(R.array.currency_name);
adapter= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, currency_name);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
OnItemSelectedListener listener = new CurrencySelectedListener();
spin1 = (Spinner)findViewById(R.id.spinner1);
spin1.setAdapter(adapter);
spin1.setOnItemSelectedListener(listener);
spin2 = (Spinner)findViewById(R.id.spinner2);
spin2.setAdapter(adapter);
spin2.setOnItemSelectedListener(listener);
}
private void calculateSum() {
String [] rates = getResources().getStringArray(R.array.currency_rate);
int index1 = spin1.getSelectedItemPosition();
int index2 = spin2.getSelectedItemPosition();
double rate1 = Double.parseDouble( rates[index1] );
double rate2 = Double.parseDouble( rates[index2] );
EditText editAmount = (EditText) findViewById(R.id.editText1);
if (!TextUtils.isEmpty(editAmount.getText().toString())) {
double amount = Double.valueOf(editAmount.getText().toString());
double totalRate = amount * rate1 / rate2;
TextView totalRateText = (TextView)findViewById(R.id.editText2);
totalRateText.setText("" + totalRate);
}
}
private class CurrencySelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
calculateSum();
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
}
答案 0 :(得分:1)
您的editAmount.getText().toString()
值为NULL
(空)。而且您仍尝试将此值转换为DOUBLE
,以便获得NumberFormatException
。
在解析之前检查editText值:
if(!editAmount.getText().toString().equals(""))
{
//Do your job
}
或者另一种方式是
if (!TextUtils.isEmpty(editAmount.getText().toString())) {
//Do your job
}