0

我试图从 Fragment 中的网站获取数据但不起作用,错误是 android.os.NetworkOnMainException

fetchData() 期间的进程错误;

Tab2Fragment.java

public class Tab2Fragment extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        if (container == null) {

            return null;
        }
        Log.i("Tab2","Creating Tab 2" );

        LinearLayout li = (LinearLayout) inflater.inflate(R.layout.tab_frag2_layout, container, false);
        try {
            fetchData();
        } catch (IOException e) {

        }
        return li;


    }



    public void fetchData() throws IOException{
            Log.i("Fetching!","JSOUP");
            try{
                HttpClient client = new DefaultHttpClient();
                String URL = "http://";
                HttpGet request = new HttpGet(URL);
                HttpResponse response = client.execute(request);

                String html = "";
                InputStream in = response.getEntity().getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                StringBuilder str = new StringBuilder();
                String line = null;
                while((line = reader.readLine()) != null)
                {
                    str.append(line);
                }
                in.close();
                html = str.toString();
                setTexts(html);

            }
            catch(Exception e){
                Log.i("Error!","JSOUP");
            }


        }

我应该怎么做才能将网站数据提取到碎片化的选项卡中。

4

1 回答 1

1

错误在这里说明了一切;您不能在主线程上运行任何网络操作。解决此问题的一种方法是将您的网络代码放入AsyncTaskhttp://developer.android.com/reference/android/os/AsyncTask.html

于 2013-10-05T17:32:06.633 回答