Разбор - значение не отображается в textView как результат, даже если исключение обрабатывается

89
9

Я работаю над конвертером валют, используя yahoo finance api следующим образом -

 public void Currency() {
spin_currency = (Spinner) findViewById(R.id.myspin);
toSpin_currency = (Spinner) findViewById(R.id.myspin1);

ArrayAdapter<CharSequence> adapterC = ArrayAdapter.createFromResource(this, R.array.name,
android.R.layout.simple_spinner_item);
adapterC.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
spin_currency.setAdapter(adapterC);
spin_currency.setSelection(142);
toSpin_currency.setAdapter(adapterC);
toSpin_currency.setSelection(59);
spin_currency.setOnItemSelectedListener(new spinOne(1));
toSpin_currency.setOnItemSelectedListener(new spinOne(2));
cd = new ConnectionDetector(getApplicationContext());
btnConv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
if (from == to) {
Toast.makeText(getApplicationContext(), "Invalid conversion", Toast.LENGTH_LONG).show();
etOutput.setText(null);
} else {
if (isInternetPresent) {

new DownloadData().execute();
} else {

// Print message for No Internet Connection !
Toast.makeText(getApplicationContext(), "Please check your internet connection", Toast.LENGTH_LONG).show();
}
}
}
});
}

public String getJson(String url)throws ClientProtocolException, IOException {

StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}

class DownloadData extends AsyncTask<Void, Integer, String> {
ProgressDialog pd = null;

@Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(Temperature.this);
pd.setTitle("Converting...");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.show();

long delayInMillis = 10000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
pd.dismiss();
}
}, delayInMillis);
}

@Override
protected String doInBackground(Void... params) {
String s;
String exResult = "";
final String val[];
val = getResources().getStringArray(R.array.value);
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22" + val[from] + val[to] + "%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
System.out.println(exResult);
}catch(JSONException e){
// TODO Auto-generated catch block
e.printStackTrace();
}catch(ClientProtocolException e){
// TODO Auto-generated catch block
e.printStackTrace();
}catch(IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}catch(NumberFormatException e) {
e.printStackTrace();
}
return exResult;

}
@Override
protected void onPostExecute(String exResult) {
super.onPostExecute(exResult);
pd.dismiss();

System.out.println("theResult:" + exResult);
if (etInput.getText().toString().trim().length() > 0) {
if (etInput.getText().toString().equals(".") || etInput.getText().toString().equals("-.") || etInput.getText().toString().equals("-")) {
Toast.makeText(getApplicationContext(), "Please enter a valid value to convert", Toast.LENGTH_LONG).show();
} else {
Double cur = Double.parseDouble(etInput.getText().toString());
etOutput.setText(String.valueOf(Double.parseDouble(exResult) * cur));
}
} else {
Toast.makeText(getApplicationContext(), "Please enter a valid value", Toast.LENGTH_LONG).show();
etOutput.setText(null);
}
}
@Override
protected void onCancelled() {
pd.dismiss();
super.onCancelled();
}
}
private class spinOne implements OnItemSelectedListener {
int ide;

spinOne(int i) {
ide = i;
}

public void onItemSelected(AdapterView<?> parent, View view,
int index, long id) {
if (ide == 1)
from = index;
else if (ide == 2)
to = index;

}

public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}

Но это вызывало мое крах приложения каждый раз, когда я пытаюсь преобразовать. Ниже приведены журналы ошибок - java.lang.NumberFormatException: недопустимый double: "" в java.lang.StringToReal.invalidReal(StringToReal.java:63) в java.lang.StringToReal.parseDouble(StringToReal.java:248) в java.lang.Double.parseDouble(Double.java:295) в com.example.rahulshaw.convotemp.Temperature $ DownloadData.onPostExecute(Temperature.java:327) в com.example.rahulshaw.convotemp.Temperature $ DownloadData.onPostExecute(Temperature.java: 268) на android.os.AsyncTask.finish(AsyncTask.java:632) на android.os.AsyncTask.access $ 600 (AsyncTask.java:177) на android.os.AsyncTask $ InternalHandler.handleMessage(AsyncTask.java:645 ) на android.os.Handler.dispatchMessage(Handler.java:102) на android.os.Looper.loop(Looper.java:136) на android.app.ActivityThread.main(ActivityThread.java:5113) на java.lang.reflect.Method.invokeNative(Native Method) в java.lang.reflect.Method.invoke(Method.java:515) в com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:793) at com.android.internal.os.Zygot eInit.main(ZygoteInit.java:609) в dalvik.system.NativeStart.main (собственный метод)

Затем я использовал следующий оператор в приведенном выше коде -

if(!exResult.equals(""){}

и теперь это -

 public void Currency() {
spin_currency = (Spinner) findViewById(R.id.myspin);
toSpin_currency = (Spinner) findViewById(R.id.myspin1);

ArrayAdapter<CharSequence> adapterC = ArrayAdapter.createFromResource(this, R.array.name,
android.R.layout.simple_spinner_item);
adapterC.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
spin_currency.setAdapter(adapterC);
spin_currency.setSelection(142);
toSpin_currency.setAdapter(adapterC);
toSpin_currency.setSelection(59);
spin_currency.setOnItemSelectedListener(new spinOne(1));
toSpin_currency.setOnItemSelectedListener(new spinOne(2));
cd = new ConnectionDetector(getApplicationContext());
btnConv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
if (from == to) {
Toast.makeText(getApplicationContext(), "Invalid conversion", Toast.LENGTH_LONG).show();
etOutput.setText(null);
} else {
if (isInternetPresent) {

new DownloadData().execute();
} else {

// Print message for No Internet Connection !
Toast.makeText(getApplicationContext(), "Please check your internet connection", Toast.LENGTH_LONG).show();
}
}
}
});
}

public String getJson(String url)throws ClientProtocolException, IOException {

StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}

class DownloadData extends AsyncTask<Void, Integer, String> {
ProgressDialog pd = null;

@Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(Temperature.this);
pd.setTitle("Converting...");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.show();

long delayInMillis = 10000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
pd.dismiss();
}
}, delayInMillis);
}

@Override
protected String doInBackground(Void... params) {
String s;
String exResult = "";
final String val[];
val = getResources().getStringArray(R.array.value);
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22" + val[from] + val[to] + "%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
System.out.println(exResult);
}catch(JSONException e){
// TODO Auto-generated catch block
e.printStackTrace();
}catch(ClientProtocolException e){
// TODO Auto-generated catch block
e.printStackTrace();
}catch(IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}catch(NumberFormatException e) {
e.printStackTrace();
}
return exResult;

}
@Override
protected void onPostExecute(String exResult) {
super.onPostExecute(exResult);
pd.dismiss();

System.out.println("theResult:" + exResult);
if (etInput.getText().toString().trim().length() > 0) {
if (etInput.getText().toString().equals(".") || etInput.getText().toString().equals("-.") || etInput.getText().toString().equals("-")) {
Toast.makeText(getApplicationContext(), "Please enter a valid value to convert", Toast.LENGTH_LONG).show();
} else {
if(!exResult.equals("")) {
Double cur = Double.parseDouble(etInput.getText().toString());
etOutput.setText(String.valueOf(Double.parseDouble(exResult) * cur));
}
}
} else {
Toast.makeText(getApplicationContext(), "Please enter a valid value", Toast.LENGTH_LONG).show();
etOutput.setText(null);
}
}
@Override
protected void onCancelled() {
pd.dismiss();
super.onCancelled();
}
}
private class spinOne implements OnItemSelectedListener {
int ide;

spinOne(int i) {
ide = i;
}

public void onItemSelected(AdapterView<?> parent, View view,
int index, long id) {
if (ide == 1)
from = index;
else if (ide == 2)
to = index;

}

public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}

И теперь приложение перестало сбой, но оно не показывает значение в etOutput.

Что мне делать? Я искал весь stackoverflow, но не получал решение. Надеюсь, я получу здесь.

спросил(а) 2016-03-02T20:51:00+03:00 5 лет, 3 месяца назад
0
Ваш ответ
Введите минимум 50 символов
Чтобы , пожалуйста,
Выберите тему жалобы:

Другая проблема