how to add progress dialog in inner class fragment

400 Views Asked by At

I want create progressdialog in fragment but keep showing error is has leaked window com.android.internal.policy.impl.phonewindow that was originally added here. please help and this my code

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

    @Override
    protected void onPreExecute() {
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("retrieving...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
    }

    @Override
    protected String doInBackground(String... params) {
        try {
            modelPost.setDataVouchers();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String result = modelPost.resultString;
        if (result.length() != 0) {
            progressDialog.dismiss();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        progressDialog.dismiss();
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                fillDaftarHarga();
            }
        });
    }
}
2

There are 2 best solutions below

1
On
leaked window com.android.internal.policy.impl.phonewindow that was originally added here.

Above error showing because you are calling progressDialog.dismiss(); on doInBackground.

1
On

check is progress dialog is showing or not and you cant touch UI thread in doInBackground

    @Override 
    protected void onPreExecute() { 
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("retrieving..."); 
        progressDialog.setIndeterminate(false); 
        progressDialog.setCancelable(false); 
        progressDialog.show();
    } 

    @Override 
    protected String doInBackground(String... params) {
        try { 
            modelPost.setDataVouchers(); 
        } catch (JSONException e) {
            e.printStackTrace();
        } 
        String result = modelPost.resultString;
        return null; 
    } 

    @Override 
    protected void onPostExecute(String result) {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        } 
        getActivity().runOnUiThread(new Runnable() {
            @Override 
            public void run() { 
                fillDaftarHarga(); 
            } 
        }); 
    } 
}