Asynk task doesnt execute doinBackground

After the help of many people, i got this code: but im facing two problems 1 - Seems that thread sleep only affects the thread not the message in progress dialog, so Tarea finalizada cant be seen as appear and disappear so quickly. If i set a message of Tarea inicializada ( begining task) it cant be shown...if i put in background it doesnt show, and if i put it after "Cargando datos por favor espere" ( loading data please wait) it shows Tarea inicializada but not Cargando datos. I need some trick to view the different messages...

Ideally would be: - "Cargando datos por favor espere" ( two seconds) - Tarea inicializada ( two seconds) - Tarea finalizada ( two seconds). - Dismiss and return to main activity

Thanks again

class ServicioInicial extends AsyncTask < Void, Void, Void> { private Context mContext;

ProgressDialog mProgress;
private ServicioInicialFinalizado mCallback;

public ServicioInicial( Context context) {
    this.mContext=context;
    this.mCallback= ( ServicioInicialFinalizado) context;
}


@Override
protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();
    mProgress= new ProgressDialog(mContext);
    mProgress.setMessage("Cargando contactos...Por favor espere");
    mProgress.show();
   // mProgress.setMessage ("Tarea comenzada");

}


@Override
protected Void doInBackground(Void... resultado) {


    try 
    {
        //Aqui simulo un calculo supercomplicado y lo ralentizamos  a 500 ms por numero


          // mProgress.setMessage("Tarea comenzada");

            //Reseteo la agendaGlobal
            AgendaGlobal.getInstance().miAgenda.clear();

            AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Belen", "c/ Diego Madrazo","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.aguila));
            AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Daniel", "c/ Diego Madrazo","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.caballo));
            AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Eduardo", "c/ Segovia","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.camaleon));
            AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Belen", "c/ Diego Madrazo","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.aguila));
            AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Daniel", "c/ Diego Madrazo","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.caballo));
            AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Eduardo", "c/ Segovia","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.camaleon));
            AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Belen", "c/ Diego Madrazo","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.aguila));
            AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Daniel", "c/ Diego Madrazo","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.caballo));
            AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Eduardo", "c/ Segovia","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.camaleon));
         //   resultado[] = (Integer)(Math.random()*(3))+1;// numero = (int) (Math.random() *6) + 1; para un dado 

          //  mProgress.setMessage("Resultado Int:" + resultado);

           // resultado = (Integer) resultado;  // convierto a entero me aseguro
             Thread.sleep(3000);

            //mProgress.setMessage ("Tarea finalizada");

           //SystemClock.sleep(1000);


    } catch (Exception e) {
        e.printStackTrace();
        }

    // mProgress.setMessage ("Tarea finalizada");
    return null;
    }


@Override
protected void onCancelled(Void result) {
    // TODO Auto-generated method stub
    super.onCancelled(null);
}


@Override
protected void onPostExecute(Void result) {

    mProgress.setMessage ("Tarea finalizada");

    try {
        Thread.sleep (3000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    mProgress.dismiss();
    /*if(mProgress != null){
        mProgress.dismiss();
        }*/
    //Aqui es donde devolvemos los datos a donde nos llama
    mCallback.onAcabeInicializacion(5);
    super.onPostExecute(null);
}


@Override
protected void onProgressUpdate(Void... values) {
    // TODO Auto-generated method stub
//mProgress.setMessage( values[0]);
    //super.onProgressUpdate(values);
}

}

Upvotes: 0

Views: 152

Answers (2)

max59
max59

Reputation: 606

You need to extend AsyncTask <Void, String, Void> and use OnProgressUpdate to update the messages.

Make these changes in your class:

class ServicioInicial extends AsyncTask <Void, String, Void> {

private Context mContext;

ProgressDialog mProgress;
private ServicioInicialFinalizado mCallback;

public ServicioInicial( Context context) {
this.mContext=context;
this.mCallback= (ServicioInicialFinalizado) context;
}


@Override
protected void onPreExecute() {
super.onPreExecute();
mProgress= new ProgressDialog(mContext);
mProgress.setMessage("Cargando contactos...Por favor espere");
mProgress.show();
}


@Override
protected Void doInBackground(Void... resultado) {

try 
{
    Thread.sleep(2000);

        AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Belen", "c/ Diego Madrazo","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.aguila));
        AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Daniel", "c/ Diego Madrazo","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.caballo));
        AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Eduardo", "c/ Segovia","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.camaleon));
        AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Belen", "c/ Diego Madrazo","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.aguila));
        AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Daniel", "c/ Diego Madrazo","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.caballo));
        AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Eduardo", "c/ Segovia","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.camaleon));
        AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Belen", "c/ Diego Madrazo","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.aguila));
        AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Daniel", "c/ Diego Madrazo","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.caballo));
        AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Eduardo", "c/ Segovia","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.camaleon));

} catch (Exception e) {
    e.printStackTrace();
}

  publishProgress("Tarea inicializada");
    try {
        Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
     }

publishProgress("Tarea finalizada");
    try {
        Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
     }

return null;
}

@Override
protected void onPostExecute(Void result) {

if(mProgress != null){
mProgress.dismiss
}

mCallback.onAcabeInicializacion(5);
super.onPostExecute(result);
}


@Override
protected void onProgressUpdate(String... values) {
mProgress.setMessage(values[0]);
super.onProgressUpdate(values);
}
}

and run your app again.

EDIT:

To clear the ArrayList add this to your activity:

@Override
public void onStop() {
  super.onStop();
  miAgenda.clear();  //Clear ArrayList
}

Upvotes: 0

Buendiadas
Buendiadas

Reputation: 851

When you're on doInBackgroundMethod you are working on a Thread apart from the UI thread so you can't just make anything to update your visual interface from there. So, there's no way to change it on doInBackground.

Instead, you can use OnPreExecute and OnPostExecute to deal with your progress. For what I think you're trying to it would be something like:

private Context mContext;

ProgressDialog mProgress;
private ServicioInicialFinalizado mCallback;

public ServicioInicial( Context context) {
    this.mContext=context;
    this.mCallback= ( ServicioInicialFinalizado) context;
}


@Override
protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();
   mProgress= new ProgressDialog(mContext);
   mProgress.setMessage("Cargando contactos...Por favor espere");
mProgress.show();

mProgress.setMessage("Tarea comenzada");

}




@Override
protected Void doInBackground(Void... resultado) {


    try 
   {
       //Aqui simulo un calculo supercomplicado y lo ralentizamos  a 500 ms por numero




        AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Belen", "c/ Diego   Madrazo","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.aguila));
        AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Daniel", "c/ Diego Madrazo","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.caballo));
        AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Eduardo", "c/ Segovia","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.camaleon));
        AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Belen", "c/ Diego Madrazo","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.aguila));
        AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Daniel", "c/ Diego Madrazo","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.caballo));
        AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Eduardo", "c/ Segovia","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.camaleon));
        AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Belen", "c/ Diego Madrazo","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.aguila));
        AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Daniel", "c/ Diego Madrazo","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.caballo));
        AgendaGlobal.getInstance().miAgenda.add(new contactoAgenda("Eduardo", "c/ Segovia","92458", "[email protected]",true, true, false, false, true,"Familia", R.drawable.camaleon));
     //   resultado[] = (Integer)(Math.random()*(3))+1;// numero = (int) (Math.random() *6) + 1; para un dado 

      //  mProgress.setMessage("Resultado Int:" + resultado);

       // resultado = (Integer) resultado;  // convierto a entero me aseguro
        Thread.sleep(200);

        //mProgress.setMessage ("Tarea finalizada");

       SystemClock.sleep(1000);


} catch (Exception e) {
    e.printStackTrace();
    }

// mProgress.setMessage ("Tarea finalizada");
return null;
}



@Override
protected void onCancelled(Void result) {
    // TODO Auto-generated method stub
    super.onCancelled(null);
}


protected void onPostExecute() {

   mProgress.setMessage ("Result Integer en postexecute:");
     mProgress.setMessage ("Tarea terminada");
   try {

 } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
 }
 mProgress.dismiss();

//Aqui es donde devolvemos los datos a donde nos llama
mCallback.onAcabeInicializacion(5);
super.onPostExecute(null);
}


@Override
protected void onProgressUpdate(Void... values) {
   // TODO Auto-generated method stub
 //  mProgress.setMessage( values[0]);
   //super.onProgressUpdate(values);
}

If your mProgress is not updating in the method onPostExecute, that's because your doInBackground is not finishing doing it's work, so take a look at that point, could be sth with your sleepers.

Upvotes: 1

Related Questions