Search code examples
androidlistviewandroid-asynctaskdialogfragment

How to execute AsyncTask on DialogFragment dismiss?


What I want to do is, I guess at least, refresh a ListView when DialogFragment is being dismissed. Whole refresh process is in my AsyncTask. I found actually a lot questions/answers but nothing helpful in my case.

I tried:

1)onDismiss in my DialogFragment, get instance of AsyncTask local class and execute it. But I got bunch of errors and I think because I tryed to create a new Activity and each time dialog is dismissed, what actually makes no sense and futhermore eats memory a lot.

@Override
    public void onDismiss(DialogInterface dialog) {
        MainActivity outterObject = new MainActivity();
        MainActivity.LoadApplications buffer = outterObject.new LoadApplications();
        buffer.execute();
    }

2)onResume in MainActivity, because I thought Activity goes into state 'paused' when Dialog appears. But it only refreshes ListView when I close and open my app again.

@Override
    protected void onResume() {
        super.onResume();
        new LoadApplications().execute();
    }

Solution

  • Instantiating an Activity the way you do in your onDismiss method is just wrong. There should never be the need to do that.

    It looks like you need a way to communicate between your DialogFragment and Activity. This exact topic is presented clearly in the docs. In you case, this could be a potential implementation:

    interface Refresher {
      void onRefresh();
    }
    
    class MainActivity extends Activity implements Refresher {
    
      // ... 
    
      void onRefresh() {
        new LoadApplications().execute();
      }  
    
    }
    
    class MyDialogFragment extends DialogFragment {
    
      private Refresher mRefresher;
    
      @Override
      public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
          mRefresher = (Refresher) activity;
        } catch (ClassCastException ex) {
          throw new ClassCastException("Activity must implement Refresher interface!");
        }
      }
    
      @Override
      public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        mRefresher.onRefresh();
      }
    
    }