我正在尝试从Android应用程序中获取Web服务中的xml。我正在运行此代码,但错误消息是'应用程序已意外停止。请再试一次'。我不确定这是一个应用程序异常,因为代码的每个代码都在try块中。这是什么错误?
public class AndroidTest extends Activity {
private static final String URL = "http://webservice.url/is/here.aspx";
TextView v;
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
v = new TextView(this);
setContentView(v);
new Obtainer().execute();
} catch (Exception ex) {
Toast.makeText(this, ex.toString(), Toast.LENGTH_LONG).show();
}
}
private class Obtainer extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(URL));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line + "\n");
}
in.close();
v.setText(sb.toString());
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show();
}
return null;
}
}
}
编辑:现在它抛出异常android.os.NetworkOnMainThreadException虽然创建了这个类(Obtainer)来修复它。
答案 0 :(得分:0)
答案非常简单 - 我们无法在非ui线程中运行Toast的show方法,我们也无法在其中使用TextView。