0

I have a problem when try to run asynctask. The error appears sometimes, for example, if I run 20 times the asynctask the error appears 1 or 2. I think the problem is with the ProgressDialog (trying to close when there is no Dialog running) but I couldn't solved it .

The error log said:

E/WindowManager: android.view.WindowLeaked: Activity com.app.GestionarTurnos has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{26d38b91 V.E..... R......D 0,0-160,180} that was originally added here
                                                                           at android.view.ViewRootImpl.<init>(ViewRootImpl.java:375)
                                                                           at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:271)
                                                                           at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
                                                                           at android.app.Dialog.show(Dialog.java:298)
                                                                           at com.app.CalcularHorariosDisponiblesComplejo$CalcularHorariosComplejoAsyncTask.onPreExecute(CalcularHorariosDisponiblesComplejo.java:110)

This is my code of my asynctask from CalcularHorariosDisponiblesComplejo.java:

public MyAsyncTask(Context context, String idComplejoSeleccionado, String idCancha, String nombreComplejo, String idUsuarioComplejo, String idPais, String dia, String mes, String anio) {
        super();
        this.context = context;
        this.idComplejoSeleccionado = idComplejoSeleccionado;
        this.idCanchaSeleccionada = idCancha;
        this.nombreComplejo = nombreComplejo;
        this.idUsuarioComplejo = idUsuarioComplejo;
        this.idPais = idPais;
        this.dia = Integer.parseInt(dia);
        this.mes = Integer.parseInt(mes);
        this.anio = Integer.parseInt(anio);

        Calendar cl = Calendar.getInstance(TimeZone.getTimeZone(String.valueOf(65)));
        cl.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dia));
        cl.set(Calendar.MONTH, Integer.parseInt(mes));
        cl.set(Calendar.YEAR, Integer.parseInt(anio));
        this.dayOfWeek = cl.get(Calendar.DAY_OF_WEEK);

        dialog = new ProgressDialog(context, R.style.ProgressDialogTheme);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        this.dialog.show();
    }
    protected String doInBackground(String... args) {
        jsonCalcularHorariosComplejo = null;
        fechaSeleccionada = (String.valueOf(anio)) + "-" + (String.valueOf(mes + 1)) + "-" + (String.valueOf(dia));

        try {
            jsonCalcularHorariosComplejo = JSONParser.readJsonFromUrl(url.concat(fechaSeleccionada+"&idCancha="+idCanchaSeleccionada+"&idUsuario="+idUsuarioComplejo+"&idComplejo="+idComplejoSeleccionado+"&dayOfWeek="+dayOfWeek+"&idPais="+idPais));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
    protected void onPostExecute(String file_url) {
        if (!esCancelado) {
            if(jsonCalcularHorariosComplejo == null){
                Toast toast = Toast.makeText(context, "Not possible connect with the server. Try it again", Toast.LENGTH_LONG);
                toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                toast.show();
                Intent intent = new Intent(context, SeleccionarCanchaComplejo.class);
                intent.putExtra("idComplejo", idComplejoSeleccionado);
                intent.putExtra("nombreComplejo", nombreComplejo);
                intent.putExtra("idPais", idPais);
                intent.putExtra("idUsuarioComplejo", idUsuarioComplejo);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                context.startActivity(intent);
                ((Activity)context).finish();
            }
            else{
                try {
                    // Verifica que se cargaron datos
                    int success;
                    success = jsonCalcularHorariosComplejo.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        diaHoy = Integer.parseInt(jsonCalcularHorariosComplejo.getString(TAG_DIAHOY));
                        mesHoy = Integer.parseInt(jsonCalcularHorariosComplejo.getString(TAG_MESHOY));
                        anioHoy = Integer.parseInt(jsonCalcularHorariosComplejo.getString(TAG_ANIOHOY));
                        horaActual = jsonCalcularHorariosComplejo.getString(TAG_HORA);
                        todosLosTurnos = jsonCalcularHorariosComplejo.getJSONArray(TAG_TODOS_LOS_TURNOS);

                        for (int i = 0; i < todosLosTurnos.length(); i++) {
                            turnoAux = todosLosTurnos.getJSONObject(i);
                            // Guardo en variables los datos del objeto
                            String hora = turnoAux.getString(TAG_HORA);
                            int canchaFK = Integer.parseInt(turnoAux.getString(TAG_CANCHAFK));
                            int usuarioFK = Integer.parseInt(turnoAux.getString(TAG_USUARIOFK));
                            int reservado = Integer.parseInt(turnoAux.getString(TAG_RESERVADO));
                            String fecha = turnoAux.getString(TAG_FECHA);
                            String nombreAuxiliar = turnoAux.getString(TAG_NOMBREAUXILIAR);
                            int noAsistio = Integer.parseInt(turnoAux.getString(TAG_NOASISTIO));
                            String fechaDeReserva = turnoAux.getString(TAG_FECHADERESERVA);
                            String telefonoAux = turnoAux.getString(TAG_TELEFONO);
                            String estado = turnoAux.getString(TAG_ESTADO);
                            Turno turno = new Turno(hora, canchaFK, usuarioFK, reservado, fecha, nombreAuxiliar, noAsistio, fechaDeReserva, telefonoAux, estado);
                            todosMisTurnos.add(turno);
                        }
                    }
                }catch (JSONException e) {
                    e.printStackTrace();
                }
                Intent intent = new Intent(context, Gestionar.class);
                intent.putExtra("todosMisTurnos", (ArrayList<Turno>) todosMisTurnos);
                intent.putExtra("idComplejo", idComplejoSeleccionado);
                intent.putExtra("idCancha", idCanchaSeleccionada);
                intent.putExtra("nombreComplejo", nombreComplejo);
                intent.putExtra("idUsuarioComplejo", idUsuarioComplejo);
                intent.putExtra("idPais", idPais);
                intent.putExtra("dia", String.valueOf(dia));
                intent.putExtra("mes", String.valueOf(mes));
                intent.putExtra("anio", String.valueOf(anio));
                intent.putExtra("diaHoy", String.valueOf(diaHoy));
                intent.putExtra("mesHoy", String.valueOf(mesHoy));
                intent.putExtra("anioHoy", String.valueOf(anioHoy));
                intent.putExtra("horaActual", horaActual);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                ((Activity)context).finish();
                context.startActivity(intent);
            }
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    }
}

When I go to the error in the line java:110, is this line (on preexecute): this.dialog.show();

Somebody can help me?

Faustino Gagneten
  • 2,564
  • 2
  • 28
  • 54

4 Answers4

0

if you have more than one AsyncTask then start Progress Dialog mechanism will be changed like

First of All Do not Defined dialog.show() in onPreExceute() and onPostExecute() when you have more than one Async task and step by step execution

Rather than try to implement this things

Start Progress Dialog in Main Thread

      Start Asynctask 1
      Start Asynctask 2

      Start Asynctask 20

At the response of Asynctask 20 dismiss Progress dialog in mainThread

In between no need to start And stop asynctask

it will work

Happy codding!!!

Mohit Trivedi
  • 699
  • 3
  • 13
0
if (dialog.isShowing()) {
            dialog.dismiss();
        }

This is the problem. Put it at the start of your onPostExecute()

badrobot15
  • 176
  • 1
  • 10
0

man, you are killing activity and then try to close dialog, first do all actions in activity and then at very end kill you activity. here first this:

        context.startActivity(intent);
    }
    if (dialog.isShowing()) {
        dialog.dismiss();
    }

and only then

((Activity)context).finish();

coz for now you killed activity, and then you are trying to close dialog in non exist activity.

Stepan Maksymov
  • 2,618
  • 19
  • 31
  • i suppose you are calling this task multiple times? if so you must count instances you called in some value (increase on start and decrease on stop) - and kill activity only when last instance finish it's work – Stepan Maksymov Oct 01 '16 at 12:30
0

Your problem is well described here:

Activity has leaked window that was originally added

In general, I suggest you to take care with AsyncTasks that execute code in place of an Activity, like showing dialogs or finishing it, because it creates a strong link between the AsyncTask and the Activity. And, since the task is asynchronous to the activity, some problems may rise, for example, when the Activity no longer exists when AsyncTask finishes its background work, or when multiple AsyncTasks are dispatched from the same Activity at the same time.

Community
  • 1
  • 1
nandsito
  • 3,782
  • 2
  • 19
  • 26