androidperformanceprogressdialog

Android: progress dialog raises on close


I have made a Util class to open and close progress dialog like this

Utils.java

public class Utils {

    private static Utils util;
    private Typeface typeface;
    private ProgressDialog progressDialog;

    public static Utils getInstance(){

        if(util == null){
            util = new Utils();
        }
        return util;
    }

    public void showProgressDialog(Activity activity){

        if(progressDialog != null && progressDialog.isShowing()){
            return;
        }

        if(progressDialog == null ) {
            progressDialog = new ProgressDialog(activity);
        }
        progressDialog.setMessage("Loading...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setCancelable(false);
        progressDialog.show();
     }

public void closeProgressDialog(){
    try {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }catch(Exception e){
        e.printStackTrace();
    }
  }
}

and then i call showProgressDialog before loading data and closeProgressDialog after data has been loaded. like this

Acvitity code

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_dashboard,container,false);
    activity = getActivity();
    ButterKnife.bind(this,view);

    init();
    return view;
}

  private void init() {

    Utils.getInstance().showProgressDialog(activity);
    getPatientsList();


   //in response i am calling closeProgressDialog();
  }

 public void onPatientListResponse(String response){
         Utils.getInstance().closeProgressDialog(); // raises exception here
  }

but it raises exception in closeProgressDialog();

java.lang.IllegalArgumentException: View=com.android.internal.policy.PhoneWindow$DecorView{f7fd12e V.E...... R......D 0,0-1024,232} not attached to window manager

Solution

  • Try this,

    Anyway u r checking whether the progressDialog is already showing if yes u r just returning the control. Rather than that dismiss the progressDialog and create a new instance. Because old progressDialog may started with different context.

    public void showProgressDialog(Activity activity){
    
            if(progressDialog != null && progressDialog.isShowing()){
                progressDialog.dismiss();
                progressDialog = null;
            }
    
            if(progressDialog == null ) {
                progressDialog = new ProgressDialog(activity);
            }
            progressDialog.setMessage("Loading...");
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setCancelable(false);
    
            if(!activity.isFinishing())
               progressDialog.show();
         }