javaandroidprogressdialog

Black Screen when trying to dismiss ProgressDialog inside a Thread


The first problem was that the ProgressDialog was not showing. Then I read that I should create a Thread. I created the Thread and it worked. But now I can't dismiss the ProgressDialog. The app crashes, the screen goes black.

xGrava.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        final ProgressDialog PD = ProgressDialog.show(NovaOcc.this,"","");
        PD.setContentView(R.layout.ipp_load);
        PD.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        Thread mThread = new Thread() {
            @Override
            public void run() {
                if (ValidaDados() == true) {
                    if (GravaDados() == true) {
                        xGrava.setVisibility(View.GONE);
                        PD.dismiss();
                    }
                }
            }
        };
        mThread.start();
    }
});

Solution

  • As I see, I guess it is for Android. Generally, we use Threads when there is a long process to run, and we don't want let the view UI stuck because it is a UI Thread running.

    So to answer the question, please make sure when calling any action on view, to do it on "runOnUIThread"

    For example here, once your Thread finishes the "long" task, you can do :

    xGrava.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final ProgressDialog PD = ProgressDialog.show(NovaOcc.this,"","");
                PD.setContentView(R.layout.ipp_load);
                PD.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                Thread mThread = new Thread() {
                    @Override
                    public void run() {
                        if (ValidaDados() == true) {
                            if (GravaDados() == true) {
                                runOnUiThread(new Runnable() {
                                              @Override
                                               public void run() {
                                                    xGrava.setVisibility(View.GONE);
                                                    PD.dismiss();
                                               }
                                           }
                                 );
                            }
                        }
                    }
                };
                mThread.start();
            }
        });