Home » Android » java – Android Activity takes too long to show content

java – Android Activity takes too long to show content

Posted by: admin June 15, 2020 Leave a comment

Questions:

My Activity in onCreate() performs long computations that take some time.

In the same onCreate() I call setContentView() to set the appearance of the activity.

The point is that, since it takes a while to performs the above mentioned computations the screen of the Activity loads only after long time.

Please, any suggestion on how to avoid this?

I have tried to call setContentView() in onCreate() and start the computations in onResume(), but again the Activity screen is loaded only at the end.

How to&Answers:

There is no other way than to use e.g. an AsyncTask. The reason is that the actual rendering does not take place asynchronously; in other words, setContentView will only set some data but nothing will be displayed at that point in time.

AsyncTask, however, is not necessarily meant for “long” computations. But if your app relies on the result, and no other computations take place in parallel, it may still be the simplest way for you to achieve what you want. If not, you may have to use a Thread even.

Update Since everybody keeps bombarding the original poster with more use AsyncTask answers of various quality, I’d like to stress one more time that AsyncTask is intended for short operations (to quote the reference: a few seconds at the most) while the OP has given no indication on how long his computations really take. Also, an AsyncTask is a one-shot-only object which can only run once.

One more very important point to consider is the following. Android assigns AsyncTask a background task priority. This means that, besides the lower scheduling priority, the computations in AsyncTask will take ten times as long as if they were performed in the foreground, because Android runs all tasks which have background priority with an artificial limit of 10% CPU cycles. However, AsyncTasks can be lifted out of this group by raising its priority “just a little bit”. For an AsyncTask, it would be done like so:

public R doInBackground(I... is) {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND +
                              Process.THREAD_PRIORITY_MORE_FAVORABLE);
    ...
}

Answer:

You have to implement AsyncTask

  public class AsyncTaskActivity extends Activity implements OnClickListener {
    Button btn;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn = (Button) findViewById(R.id.button1);.
                    //because we implement OnClickListener we only have to pass "this" (much easier)
        btn.setOnClickListener(this);
    }

    public void onClick(View view){
        //detect the view that was "clicked"
        switch(view.getId())
        {
          case R.id.button1:
              new LongOperation().execute("");
          break;

        }

    }

    private class LongOperation extends AsyncTask<String, Void, String> {

          @Override
          protected String doInBackground(String... params) {
                for(int i=0;i<5;i++) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                return "Executed";
          }      

          @Override
          protected void onPostExecute(String result) {
                TextView txt = (TextView) findViewById(R.id.output);
                txt.setText("Executed"); // txt.setText(result);
                //might want to change "executed" for the returned string passed into onPostExecute() but that is upto you
          }

          @Override
          protected void onPreExecute() {
          }

          @Override
          protected void onProgressUpdate(Void... values) {
          }
    }

Answer:

If all computations take long time to execute, your UI is ‘locked’ and not updated.

You need to do all long work in an AsyncTask

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

Answer:

call setContentView(layoutID) in onCreate method before you start initializing views, create a AsyncTask and start AsyncTask thread after you called setContentView in onCreate method only. Something like given below

  onCreate(....){
    --
    --
    setContentView(layoutID);
    ---
    --
    new asynchTask(); // load your ui in AsyncTask by creating an inner class in your activity by extending AsyncTask class

    }

here is a tutorial of how to implement AsyncTask