Search code examples
androidandroid-fragmentsandroid-listviewandroid-asynctask

Fragments load data too slow


I am working on a project which is totally based on Fragments with NavigationDrawer. Each fragment gets data from web services. A single fragment takes here so much time to load data. And one of all the fragments is a Fragment which has 10+ fragments using TabLayout and ViewPager and each fragment is showing data in a ListView and also takes so much time to load. I've tried many approaches and last approach is like:

public class CommodityFragment extends android.support.v4.app.Fragment implements SearchView.OnQueryTextListener {
private boolean isViewShown = false;

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (getView() != null) {
        isViewShown = true;
    } else {
        isViewShown = false;
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.equity_activity, container, false);
    act = this.getActivity();
    return view;
}

public void onActivityCreated(Bundle savedInstanceState1) {
    super.onActivityCreated(savedInstanceState1);
    setHasOptionsMenu(true);
    list = (ListView) view.findViewById(R.id.list_equity);
    empty_text = (TextView) view.findViewById(R.id.empty);
    if (Utils.isNetworkAvailable(getActivity())) {
        if (catListDao.size() > 0) {
            adapter = new AdvisorsAdapter(act,R.layout.custom_equity, catListDao);
            list.setAdapter(adapter);
        } else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // do some work here
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (!isViewShown) {
                                new FetchAllData(getActivity(), 2).execute();
                            }
                        }
                    });
                }
            }).start();
        }
    } else {
        CustomToast toast = new CustomToast(getActivity(), "There is no internet connection!");
    }

}
}

Solution

  • Calling execute() on an AsyncTask adds it to a que shared by all of your AsyncTask's. This means that each request to the server is made one at a time. By instead adding your task to a thread pool you can have many tasks executing at once.

    myTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    

    For managing your network requests it would usually be better to use a library designed for doing so. I personally use Retrofit however others such as Volley, RoboSpice and OkHttp are a fine choice also.