我正在使用谷歌获取货币并使用 json 我应该获取货币的价值,但出现错误。“可惜,xxx停了。”
String result = null;
我的异步任务
private class usdjson extends AsyncTask<URL, Void, JSONObject> {
@Override
protected JSONObject doInBackground(URL... urls) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://www.google.com/ig/calculator?hl=en&q=2GBP=?USD");
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
Log.e("Log", result);
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
JSONObject object = null;
try {
object = new JSONObject(result);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray Jarray = null;
try {
Jarray = object.getJSONArray("lhs");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject Jasonobject = null;
for (int i = 0; i < Jarray.length(); i++) {
try {
Jasonobject = Jarray.getJSONObject(i);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return Jasonobject;
}
@Override
protected void onPostExecute(JSONObject jsonData) {
value.setText(result);
}
}
我的按钮点击
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new usdjson().execute();
}
});
日志猫:
08-30 21:21:51.769: E/AndroidRuntime(28903): FATAL EXCEPTION: AsyncTask #1
08-30 21:21:51.769: E/AndroidRuntime(28903): java.lang.RuntimeException: An error occured while executing doInBackground()
08-30 21:21:51.769: E/AndroidRuntime(28903): at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-30 21:21:51.769: E/AndroidRuntime(28903): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
08-30 21:21:51.769: E/AndroidRuntime(28903): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
08-30 21:21:51.769: E/AndroidRuntime(28903): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
08-30 21:21:51.769: E/AndroidRuntime(28903): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-30 21:21:51.769: E/AndroidRuntime(28903): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)