Error ProgressDialog along with threads on Android

1

I have the following structure in my class:

public class Registro extends AppCompatActivity {

private ProgressDialog progressDialog;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(...);
    enviar=(Button)findViewById(R.id.enviarDatos);

    enviar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                try {
                    enviarDatos();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        }
    });

private void enviarDatos() throws IOException, InterruptedException {

    progressDialog = ProgressDialog.show(Registro.this, "Registrando", "Espere, por favor...");

    final Thread t=new Thread(new Runnable() {
        @Override
        public void run() {
            ...codigo...
        }
    });

    final Thread pb=new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            progressDialog.dismiss();
            progressDialog=null;
            ...codigo...
        }
    }):
}
}

The problem I have is that I get an error in the ProgressDialog creation line, "... you've leaked window", all the time.

I simply put the structure of the class because in another that I have identical, I do it well, the only difference is that in the other, I call enviarDatos() directly from onCreate() directly (no listener or anonymous class or nothing) and so it does not give me problems.

If the problem lies in this last comment, what can I do to solve it? Otherwise, what is the probable cause for me to tell you this error?

    
asked by Josedu 20.04.2017 в 17:33
source

1 answer

2

This error arises when the Activity that started the ProgressDialog , does not exist, is paused or was destroyed.

As a solution to avoid this problem, define a variable to determine when the% co_of% that creates the Activity is visible

private static boolean foreground = true; //valida si permite mostrar el ProgressDialog.

and implements the following methods:

@Override
protected void onPause() {
    foreground = false;
  super.onPause();
}

@Override
protected void onResume() {
    foreground = true;
  super.onResume();
}

and validate this way if the ProgressDialog is shown or not, to avoid the error ProgressDialog :

  if(foreground){
       progressDialog = ProgressDialog.show(Registro.this, "Registrando", "Espere, por favor...");
   }
    
answered by 20.04.2017 в 17:40