-5

所以我在下面的屏幕截图中有这部分代码导致类型 IOExceptions。

http://southwestdesign.org.uk/Code.jpg

我被告知我需要将它包装在一个 try-catch 块中,用 try catch 包装每个单独的块可以消除错误,但在 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);
        }
    }

多谢你们。

4

3 回答 3

4

您似乎在 UI 线程上执行网络 IO,这是一个坏主意。因此,从 Android 2.3 开始,系统“捕获”了这一点并终止了该进程。

你应该把

 HttpResponse response = client.execute(request);

进入后台线程,例如使用AsyncTask.

于 2012-10-28T17:21:24.607 回答
0
try {

   //do something here
   //call method

}catch (IOException ioe){

// do something else
// log ioe

}
于 2012-10-28T17:19:55.467 回答
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在单独的线程上完成此操作。

于 2012-10-28T17:21:16.303 回答