android.os.NetworkOnMainThreadException异常

时间:2014-10-15 21:58:04

标签: android android-asynctask dynamic-loading

我试图实现listView动态加载,所以在Launch i执行AsyncTask,然后OnScrollListener我调用另一个asynctask来加载更多视图。但是我得到了一个执行。

这是我的代码:

public class HomeFragment扩展了Fragment {

private ListView lv;
private FeedListAdapter adapter;
private List<Reclamation> data;
ProgressDialog pDialog;
View loadMoreView;

// Flag for current page
int current_page = 1;

private String URL = Const.GET_FEEDS_URL + "/?page=1";

public HomeFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.home_fragment, container,
            false);
    setHasOptionsMenu(true);

    lv = (ListView) rootView.findViewById(R.id.list_of_feed);
    data = new ArrayList<Reclamation>();

    new getFeedsTask().execute();


    loadMoreView = ((LayoutInflater) getActivity().getSystemService(
            Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.loadmore,
            null, false);

    lv.addFooterView(loadMoreView);
    adapter = new FeedListAdapter(getActivity(), data);

    lv.setOnScrollListener(new OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {

            new loadMoreListView().execute();



        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {


        }
    });

    return rootView;

}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.home_fragment, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    Fragment fragment = null;
    // Handle action bar actions click
    switch (item.getItemId()) {
    case R.id.create_new_delay:
        fragment = new ReportDelayFragment();
        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment).commit();

        }

    default:
        return super.onOptionsItemSelected(item);
    }

}

private class getFeedsTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {

        super.onPreExecute();
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Veuillez patienter!!");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        UserFunctions userFunction = new UserFunctions();
        JSONObject json = userFunction.getFeeds(URL);


        try {
            if (json != null) {
                JSONArray feeds = json.getJSONArray("feed");
                for (int i = 0; i < feeds.length(); i++) {
                    JSONObject feedObj = (JSONObject) feeds.get(i);

//添加项目

                    data.add(reclamation);

                }
                //adapter.notifyDataSetChanged();
            } else {
                if (BuildConfig.DEBUG) {
                    Log.e("JSON Data",
                            "Didn't receive any data from server!");
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;

    }

    @Override
    protected void onPostExecute(Void result) {
        pDialog.hide();
        lv.setAdapter(adapter);
        super.onPostExecute(result);
    }

}

private class loadMoreListView extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        getActivity().runOnUiThread(new Runnable() {
            public void run() {

                // increment current page
                current_page += 1;

                // Next page request
                URL = Const.GET_FEEDS_URL + "/?page=" + current_page;

                UserFunctions userFunction = new UserFunctions();
                JSONObject json = userFunction.getFeeds(URL);


                try {
                    if (json != null) {
                        JSONArray feeds = json.getJSONArray("feed");
                        for (int i = 0; i < feeds.length(); i++) {
                            JSONObject feedObj = (JSONObject) feeds.get(i);
                            //adding items

                            data.add(reclamation);

                        }
                    } else {
                        if (BuildConfig.DEBUG) {
                            Log.e("JSON Data",
                                    "Didn't receive any data from server!");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                // get listview current position - used to maintain scroll
                // position
                int currentPosition = lv.getFirstVisiblePosition();

                adapter = new FeedListAdapter(getActivity(), data);
                lv.setAdapter(adapter);
                // Setting new scroll position
                lv.setSelectionFromTop(currentPosition + 1, 0);
            }
        });
        return null;
    }

}

}

onScrollListner我得到了这个例外:

10-15 22:45:08.267:E / AndroidRuntime(19252):致命异常:主要 10-15 22:45:08.267:E / AndroidRuntime(19252):进程:com.moroccotd.mtd,PID:19252 10-15 22:45:08.267:E / AndroidRuntime(19252):android.os.NetworkOnMainThreadException 10-15 22:45:08.267:E / AndroidRuntime(19252):在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1156) 10-15 22:45:08.267:E / AndroidRuntime(19252):at java.net.InetAddress.lookupHostByName(InetAddress.java:385) 10-15 22:45:08.267:E / AndroidRuntime(19252):at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 10-15 22:45:08.267:E / AndroidRuntime(19252):at java.net.InetAddress.getAllByName(InetAddress.java:214) 10-15 22:45:08.267:E / AndroidRuntime(19252):at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137) 10-15 22:45:08.267:E / AndroidRuntime(19252):at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 10-15 22:45:08.267:E / AndroidRuntime(19252):at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 10-15 22:45:08.267:E / AndroidRuntime(19252):at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 10-15 22:45:08.267:E / AndroidRuntime(19252):at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670) 10-15 22:45:08.267:E / AndroidRuntime(19252):at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509) 10-15 22:45:08.267:E / AndroidRuntime(19252):at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 10-15 22:45:08.267:E / AndroidRuntime(19252):at com.moroccotd.mtd.backend.JSONParser.getJSONFromUrl(JSONParser.java:47) 10-15 22:45:08.267:E / AndroidRuntime(19252):at com.moroccotd.mtd.backend.UserFunctions.getFeeds(UserFunctions.java:173) 10-15 22:45:08.267:E / AndroidRuntime(19252):at com.moroccotd.mtd.HomeFragment $ loadMoreListView $ 1.run(HomeFragment.java:248) 10-15 22:45:08.267:E / AndroidRuntime(19252):在android.os.Handler.handleCallback(Handler.java:733) 10-15 22:45:08.267:E / AndroidRuntime(19252):在android.os.Handler.dispatchMessage(Handler.java:95) 10-15 22:45:08.267:E / AndroidRuntime(19252):在android.os.Looper.loop(Looper.java:157) 10-15 22:45:08.267:E / AndroidRuntime(19252):在android.app.ActivityThread.main(ActivityThread.java:5356) 10-15 22:45:08.267:E / AndroidRuntime(19252):at java.lang.reflect.Method.invokeNative(Native Method) 10-15 22:45:08.267:E / AndroidRuntime(19252):at java.lang.reflect.Method.invoke(Method.java:515) 10-15 22:45:08.267:E / AndroidRuntime(19252):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1265) 10-15 22:45:08.267:E / AndroidRuntime(19252):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081) 10-15 22:45:08.267:E / AndroidRuntime(19252):at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

你不应该在ui /主线程上进行网络操作我知道你正在使用异步任务,但这就是为什么你在这里看到你的代码的错误

getActivity().runOnUiThread(new Runnable() {public void run() {});

这使得它在ui线程上运行尽管异步任务美...我建议你删除这段代码并让异步任务工作并使用postexecute发布到ui线程..