所以我在下面的屏幕截图中看到了导致Type IOExceptions的代码段。
http://southwestdesign.org.uk/Code.jpg
我被告知我需要将它包装在try-catch块中,用try catch包装每个invididual块可以消除错误,但强制关闭Android。有人可以指出我正确的方向吗?
@Override
public void onStart() {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://1.php");
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
TextView textView = (TextView) findViewById(R.id.TextView1);
String line = "";
while ((line = rd.readLine()) != null) {
textView.append(line);
}
}
谢谢你们。
答案 0 :(得分:4)
你似乎在UI线程上做了网络IO,这是一个坏主意。因此,自从Android 2.3以来,系统“抓住”了这个并杀死了这个过程。
你应该把
HttpResponse response = client.execute(request);
进入后台线程,例如使用AsyncTask
。
答案 1 :(得分:0)
try {
//do something here
//call method
}catch (IOException ioe){
// do something else
// log ioe
}
答案 2 :(得分:0)
它应该是这样的:
@Override
public void onStart() {
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://1.php");
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
TextView textView = (TextView) findViewById(R.id.TextView1);
String line = "";
while ((line = rd.readLine()) != null) {
textView.append(line);
}
}catch (IOException ex){
}
}
更优选地使用AsyncTask
在单独的线程上完成此操作。