0

I need to show a progress indicator bar while parsing a downloading xml.

I did it downloading first, and then parsing, but I wan't to do both action parallels.

This is part of my code to do this, but i don't know how to show the pogress indicator.

   public class WS_Sincronizo  extends AsyncTask<Void,Integer,List<Alertas>>{


private Context conte;
// Variable para controlar ventana de progreso
private Sincronizacion actividad;
private Alertas user;
private long totalSize;
private WaitForCancelTask wft;
private HttpPost httpPost;
private HttpClient httpClient;
private HttpContext localContext;
private List<Alertas> resultado;
private BaseDatosHelper miBBDDHelper;
private SQLiteDatabase db;
private SincronizarXmlHelper manejadorXML;
private String fecha_bd;
private HttpEntity resEntity;

public static  double fileSize; 
private double downloaded; // number of bytes downloaded 


public WS_Sincronizo (Context conte,Object actividad, String fecha){
    this.conte=conte;
    this.actividad=(Sincronizacion) actividad;
    this.fecha_bd=fecha;
    fileSize = 0; 
    downloaded = 0; 

}


@Override
protected void onPreExecute() {
    super.onPreExecute();
    resultado=null;
    //TimeOut si exece el tiempo límite
    wft=new WaitForCancelTask(this,conte,Utiles.TimeOutWebServerSincro);
} 


@Override 
protected void onProgressUpdate(Integer... progress) { 
// TODO Auto-generated method stub 
    actividad.progreso((int) (progress[0]));

  if (progress[0].intValue()==100){
    /*** CANCELO TIMEOUT ***/
    wft.FinishWaitForCancelTask();
    }

} 


@Override
protected void onPostExecute(List<Alertas> rta) {
    super.onPostExecute(rta);
    // Envío mensaje vacio al manejador para indicar que ya terminó.

     actividad.FinSincronizacion(rta);



}


@Override
protected void onCancelled() {
    //Si había empezado una transacción la cierro
    try{
    db.releaseReference();
    }catch (Exception e) {
        // TODO: handle exception

    }


    httpPost=null;
    httpClient.getConnectionManager().shutdown();

    this.onPostExecute(null);

}

@Override
public List<Alertas> doInBackground(Void... params) {

      httpClient = new DefaultHttpClient();
      localContext = new BasicHttpContext();
      httpPost = new HttpPost(Utiles.UrlWebService + "GetSincro");


      try {  

        String version = conte.getPackageManager().getPackageInfo(conte.getPackageName(), 0).versionName; 

        multipartContent.addPart("fecha",new StringBody(fecha_bd));

        multipartContent.addPart("version",new StringBody(version));

        multipartContent.addPart("sistema",new StringBody(Utiles.SISTEMA));



    httpPost.setEntity(multipartContent);

    HttpResponse httpresponse = httpClient.execute(httpPost,localContext);

    if(httpresponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK){
        //Cancelo TimeOut porque resp es ok;


        resEntity = httpresponse.getEntity();


            if (resEntity != null) {

            fileSize = resEntity.getContentLength(); 

            //Log.d("SIZE:",MemoryStatus.formatSize((long)fileSize));
            Log.d("SIZE:",String.valueOf(fileSize));

            //Log.i("RESPONSE",EntityUtils.toString(resEntity));
                SAXParserFactory fabrica = SAXParserFactory.newInstance();
                SAXParser parser = fabrica.newSAXParser();
                XMLReader lector = parser.getXMLReader();






                try{
                    miBBDDHelper = new BaseDatosHelper(conte);
                    db=miBBDDHelper.SincronizarTablas();
                    manejadorXML = new SincronizarXmlHelper(db);
                    lector.setContentHandler(manejadorXML);
                    lector.parse(new InputSource(resEntity.getContent()));
                    // Obtengo el resultado del XML
                    resultado = manejadorXML.getListas();

                }catch (Exception e){

                }

                finally {
                    // TODO: handle exception
                    resEntity.consumeContent();
                    if (db.inTransaction()) {
                        db.endTransaction();
                    }
                    db.close();
                    miBBDDHelper.close();

                }

                if(resultado.isEmpty()) {
                    throw null;
                }
                else {
                    return resultado;
                }

                // Si dio error la RESPUESTA del SERWEB

            } else {

                throw null;
            }

            // Si no recibo la cabecera ok ,fuera
        } else {

            throw null;

        }           


    } catch (Exception e) {
        // TODO Auto-generated catch block
       // Log.d("Error",e.getMessage());
        httpClient.getConnectionManager().shutdown();
        return null;

    }



}
lolaylo21
  • 1
  • 3

2 Answers2

0

I suggest you use AsyncTask to do what u r trying. Use the doInBackground() to download and parse() while you can use the onProgressUpdate() to show the progressdialog. here is a tutorial to do the same.

http://www.shubhayu.com/android/witer-asynctask-what-why-how

or you can search for AsyncTask in the Android Developers blog.

EDIT

Declare private ProgressDialog mProgress = null; in your extended AsyncTask and then add the following assuming Progress parameter is String and Result parameter is boolean

@Override
protected void onPreExecute() {
    mProgress = ProgressDialog.show(mContext, progressTitle, mMessage);
    mProgress.setCancelable(false);
    super.onPreExecute();
}

@Override
protected void onProgressUpdate(String... progress) {
    mProgress.setMessage(progress);
}

@Override
protected void onPostExecute(Boolean result) {

    if( result ){
        mProgress.setMessage("Succesfully Downloaded and Parsed!");
    }else{
        mProgress.setMessage("Failed to download :(");
    }
    mProgress.dismiss();
    super.onPostExecute(result);
}

And in your doInBackGround(), use the following to update the progressdialog

publishProgress("your update Message");
Shubhayu
  • 13,402
  • 5
  • 33
  • 30
  • oh great! Then the rest would be very simple, I'll update the answer – Shubhayu Apr 10 '12 at 09:09
  • You can change it as per your requirement. I just gave it as a demonstration. – Shubhayu Apr 10 '12 at 09:50
  • WHat problem are you facing now? Can you put up the code of your asynctask? – Shubhayu Apr 12 '12 at 07:31
  • ok. so that is not a problem with showing the progressbar. Once you get that part working, i guess you'll be able to show the progresbar while the downloading and parsing occurs. – Shubhayu Apr 12 '12 at 09:18
  • Yes, the problem is when reading XML with SAX parser (web service), not read the bytes consumed (or downloaded) and cant publish in a progress bar the transfer.. (I am not downloading a file, I am consuming a Web Service)... I know to progress a file, but not this. – lolaylo21 Apr 12 '12 at 09:22
  • Yes, that its fine. The resEntity.getContent() is the xml. – lolaylo21 Apr 12 '12 at 11:49
  • I have been through the code but I fail to see where you are starting the progressdialog. is it the Sincronizacion thingy? if yes then what is it? – Shubhayu Apr 13 '12 at 07:43
0

Try:

public class SomeActivity extends Activity {

   private static final int PROGRESS_DIALOG_ID = 0;

   @Override
   protected Dialog onCreateDialog(int id) {
       if (id == PROGRESS_DIALOG_ID) {
           ProgressDialog dialog = new ProgressDialog(this);
           dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
           dialog.setMessage("Loading...");
           dialog.setCancelable(false);
           return dialog;
       }
       return super.onCreateDialog(id);
   }

   public void someMethod(){
       new SomeTask().execute();
   }

   class SomeTask extends AsyncTask<Void, Void, Void> {

      @Override
      protected void onPreExecute() {
           showDialog(PROGRESS_DIALOG_ID);
      }

      @Override
      protected Void doInBackground(Void... voids) {
        // download and parse
          return null;
      }
      @Override
      protected void onPostExecute(Void aVoid) {
          dismissDialog(PROGRESS_DIALOG_ID);
      }
  }
}
Vyacheslav Shylkin
  • 9,741
  • 5
  • 39
  • 34