我是 Stackoverflow 的新手。
我正在尝试制作一个单位转换器,其中函数“calculateCurrency”返回结果的 Double 值。但是 TextView "outputNumber" 的值总是根据之前的输入而变化。
例如,如果我输入 1,则 outputNumber 会更改为“null”,但是当我在 1 之后输入另一个数字时,outputNumber 会更改为应该在 1 上更改的值。但是 Toast 显示的是正确的值,即在 1 上,它显示 1,因此 myInputNumber 的值根据输入是正确的。
谁能帮我?
inputNumber.addTextChangedListener(
new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
try {
myInputNumber = Double.parseDouble(s.toString());
Double myText = calculations.calculateCurrency(myInputNumber, convertFrom, convertTo);
Toast.makeText(MainActivity.this, myInputNumber+"", Toast.LENGTH_SHORT).show();
outputNumber.setText(myText+"");
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
}
}
);
compute.calculateCurrency 的代码是:
public Double calculateCurrency(Double input, String convertFrom, String convertTo) throws ExecutionException, InterruptedException {
myCurrencyFetcher fetchCurrency = new myCurrencyFetcher();
fetchCurrency.execute(Double.toString(input), convertFrom, convertTo);
return myText;
}
class myCurrencyFetcher extends AsyncTask<String, Double, Double>{
URL url;
StringBuffer stringBuffer;
@Override
protected Double doInBackground(String... params) {
try{
Double myInputNumber = Double.parseDouble(params[0]);
String convertFrom = params[1];
String convertTo = params[2];
url = new URL("http://api.fixer.io/latest?base="+convertFrom+"&symbols="+convertTo);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
stringBuffer = new StringBuffer();
String line = "";
while((line = reader.readLine()) != null){
stringBuffer.append(line);
}
String finalJSON = stringBuffer.toString();
JSONObject parentObject = new JSONObject(finalJSON);
JSONObject finalObject = parentObject.getJSONObject("rates");
String rate = finalObject.getString(convertTo);
//String year = finalObject.getString("year");
Double myRate = Double.parseDouble(rate);
return myInputNumber*myRate;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Double result) {
super.onPostExecute(result);
Calculations.myText = result;
}
}