Search code examples
androidandroid-alertdialoglagui-thread

AlertDialog Display Lag


I have a process which takes some time to execute, deleteImages. I want the UI thread blocked while this task executes. I tried to create an AlertDialog and show it before deleteImages starts so there is not simply unexplained hang time. However, even though I call dialog.show() before the call to deleteImages, the dialog only shows after deleteImages has completed. What am I doing wrong?

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = getLayoutInflater();
View content = inflater.inflate(R.layout.deletion_dialog, null);
builder.setView(content);

AlertDialog dialog = builder.create();
dialog.show();

deleteImages(dataStringsToDelete);

Solution

  • Try running your your deleteImages(dataStringsToDelete); in async task and hide your dialog in OnPostExecute()

    Like this:

    new AsyncTask<Void, Void, Void> {
     protected Long doInBackground(Void... void) {
    
         deleteImages(dataStringsToDelete);
    
     }
    
     protected void onPostExecute(Long result) {
         dialog.dismiss();
     }
    }.execute()