[Solved] How to render a view before loading data


While I would suggest Retrofit for cloud API operations, if you want to use an AsyncTask, then that’s fine. I would also suggest a ProgressBar / Dialog rather just updating some text.

the view will not render until the task is finished

Unclear…

I found a solution online informs that I should render the view in the onPreExecute() and onPostExecute() method, so I tried the approach. Well, it does not work either

Yes, that would work, so you should show what you tried.

it seems that there is a constraint that forces the rendering work to be done only after all the AsyncTask has finished

Yes, there is a limitation that you cannot update the UI outside of the UI thread. That is why onPreExecute and onPostExecute exist.


I can guarantee those methods work.

enter image description here

public class ButtonActivity extends android.support.v7.app.AppCompatActivity implements View.OnClickListener {

    private Button button;
    private ProgressBar pg;

    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(...);

        button = (Button) findViewById(...);
        button.setOnClickListener(this);

        pg = (ProgressBar) findViewById(...);
        setLoading(false);
    }

    private void setLoading(boolean loading) {
        button.setText(loading ? "loading" : "get data");
        pg.setVisibility(loading ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onClick(View v) {
        new BackgroundTask().execute();
    }

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

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            setLoading(true);
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                // some long operation
                Thread.sleep(3000);
            } catch (InterruptedException e) { }

            return null;
        }


        @Override
        public void onPostExecute(Void result) {
            setLoading(false);
        }
    }
}

9

solved How to render a view before loading data