Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use a ProgressDialog properly with an AsyncTask without causing window leaks?
    primarykey
    data
    text
    <p>I have an AsyncTask which shows a ProgressDialog. The AsyncTask is started when the activity is started:</p> <pre><code>public class MyActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_layout); new MyTask().execute(); } // ... other code private class MyTask extends AsyncTask&lt;Void, Void, Void&gt;{ private ProgressDialog dialog = new ProgressDialog(MyActivity.this); @Override protected void onPreExecute() { dialog.show(); } @Override protected Void doInBackground(Void... voids) { // get data from a server return null; } @Override protected void onPostExecute(Void aVoid) { // call to a method in MyActivity which updates the UI. if (dialog.isShowing()) { dialog.dismiss(); } } } } </code></pre> <p>This code works perfectly, untill I rotate my screen. Which makes sense, because the context that was used to create the dialog doesn't exist anymore (because the activity is re-created when rotating), and a window leak is caused.</p> <p>The only solution I could think of isn't a really nice one: create a static instance of the task and dialog, and simply dismiss the dialog when the activity is destroyed, and recreate the dialog in the oncreate method if the task is still running.</p> <p>So how would I solve something like this without losing functionality (so the dialog must always be shown when the task is running, and rotating the device should be allowed)? </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload