0

添加了很多 tv.setText() 以便了解正在执行哪些行以及 try 块在哪里中断。'tv' 的结束结果是 4。

public class Main extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    TextView tv = (TextView) findViewById(R.id.textView);

    BufferedReader reader = null;

    try{
        tv.setText("1");
        URL url = new URL("https://www.google.com");
        tv.setText("2");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        tv.setText("3");

        StringBuilder sb = new StringBuilder();
        tv.setText("4");
        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        tv.setText("5");

        String line;
        tv.setText("6");
        while((line = reader.readLine()) != null){
            tv.append(line + "\n");
        }
    }catch (Exception e){
        //tv.setText("Exception");
    }
}

我正在使用 Android Studio,而 LogCat 是:

04-22 23:38:25.990  28870-28870/com.example.taha.url E/Trace﹕ error opening trace file: No such file or directory (2)
04-22 23:38:26.118  28870-28870/com.example.taha.url E/linker﹕ load_library(linker.cpp:759): library "libmaliinstr.so" not found
04-22 23:38:26.125  28870-28870/com.example.taha.url E/﹕ appName=com.example.taha.url, acAppName=com.android.cts.openglperf
04-22 23:38:26.125  28870-28870/com.example.taha.url E/﹕ 0
04-22 23:38:26.125  28870-28870/com.example.taha.url E/﹕ appName=com.example.taha.url, acAppName=com.android.browser
04-22 23:38:26.125  28870-28870/com.example.taha.url E/﹕ 0
4

1 回答 1

1

您不能在可以使用的主线程上执行网络操作AsyncTask,并将网络操作放在 AsyncTask 类的 doInBackground 方法中。

看看这个:http: //developer.android.com/training/basics/network-ops/connecting.html#AsyncTask

于 2015-04-22T18:55:28.160 回答