我遇到了问题。
我正在努力解决这个问题,因为没有结果:
public void getData(){
new Task().execute();
}
class Task extends AsyncTask<Void, Void, String>{
@Override
protected String doInBackground(Void... noargs) {
return null;
}
protected void onPostExecute(String result){
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.omdbapi.com/?t=True%20Grit&y=1969");
try {
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
StringBuffer zeile = new StringBuffer("");
while((line = rd.readLine()) != null){
zeile.append(line);
}
String res = zeile.toString();
Toast toast = Toast.makeText(getApplicationContext(), res, Toast.LENGTH_SHORT);
toast.show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
每次(按钮调用getDate())我得到一个例外,在我的手机上它说“不幸的是应用程序已经完成”。你知道我的错误在哪里吗?
异常是:NetworkOnMainThreadException,我该如何解决?
非常感谢你!
答案 0 :(得分:1)
您应将所有与网络相关的代码移至doInBackground()
,并在onPostExecute()
内处理网络调用的结果。以下是您的代码的外观:
class Task extends AsyncTask<Void, Void, String>{
@Override
protected String doInBackground(Void... noargs) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.omdbapi.com/?t=True%20Grit&y=1969");
try {
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
StringBuffer zeile = new StringBuffer("");
while((line = rd.readLine()) != null){
zeile.append(line);
}
String res = zeile.toString();
return res;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
protected void onPostExecute(String result){
Toast toast = Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT);
toast.show();
}
}
答案 1 :(得分:0)
onPostExecute()
和onPreExecute()
。将网络代码从onPostExecute()
移至doInBackground()
。