0

I'm trying to implement listView dynamic loading, so at Launch i execute an AsyncTask, and then OnScrollListener i call an other asynctask to load more views. But i'm getting an execption.

Here is my code:

public class HomeFragment extends 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);

//adding items

                    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 i'm gettiong this exception:

10-15 22:45:08.267: E/AndroidRuntime(19252): FATAL EXCEPTION: main 10-15 22:45:08.267: E/AndroidRuntime(19252): Process: 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): at 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): at android.os.Handler.handleCallback(Handler.java:733) 10-15 22:45:08.267: E/AndroidRuntime(19252): at android.os.Handler.dispatchMessage(Handler.java:95) 10-15 22:45:08.267: E/AndroidRuntime(19252): at android.os.Looper.loop(Looper.java:157) 10-15 22:45:08.267: E/AndroidRuntime(19252): at 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)

Najoua Mahi
  • 304
  • 3
  • 16

1 Answers1

1

you are not suppose to do network operations on the ui/Main thread i know you are using async task but this is why you get the error look at your code here

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

this makes it run on the ui thread despite async task beauty.. i'd suggest you remove this code and let async task work and use postexecute to post to the ui thread..

Elltz
  • 10,730
  • 4
  • 31
  • 59