Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activity doesnt show until Asynctask is done

I am starting an activity and calling an asynctask in onCreateView() to fetch data from a webservice and populate the data in onPostExecute(). Currently the activity doesnt load until the asynctask in the fragment finishes.

How can i display the empty form immediately and update it as the task finishes? The activity just hosts fragments and the asyntasks are in the fragments, if that makes a difference.

Fragment onCreateView():

    @Override
public View onCreateView(LayoutInflater inflater,
        ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_friends,container, false);




    return v;

}

Fragment onActivityCreated():

    @Override
public void onActivityCreated(Bundle savedInstanceState){
    super.onActivityCreated(savedInstanceState);

    //getFriends() calls a method that is an asyntask
    peopleList = getFriends();

    if (peopleList!=null){
    list = (ListView)getActivity().findViewById( R.id.friendsList);

    list.setAdapter(new FriendsAdapter(getActivity(), peopleList,"friends") );

    }
}
like image 707
TheGeekNess Avatar asked Dec 04 '25 01:12

TheGeekNess


1 Answers

This is because you are populating the data onPostExecute() which gets hooked on to the UI thread only after doInBackground() is complete. If you want to show the progress as and when things happen you need to call the publishProgress() method.

Now the publishProgress() method hooks onto the onProgressUpdate() method and this hooks onto the UI thread which updates the UI thread while doInBackground() is running. I've given a very simple example of something I did for practice sometime back - take a look at how it works. It basically keeps updating a ListActivity, one element at a time and shows this progress on screen - it does not wait until all the strings are added to display the final page:

class AddStringTask extends AsyncTask<Void, String, Void> {


    @Override
    protected Void doInBackground(Void... params) {
        for(String item : items) {
            publishProgress(item);
            SystemClock.sleep(400);
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(String... item) {
        adapter.add(items[0]);
    }

    @Override
    protected void onPostExecute(Void unused) {
        Toast.makeText(getActivity(), "Done adding string item", Toast.LENGTH_SHORT).show();
    }

}
like image 154
ucsunil Avatar answered Dec 05 '25 16:12

ucsunil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!