2012-04-10 5 views
0

Ich muss eine Fortschrittsanzeige während der Analyse eines Download-XML zeigen.Android: Zeige Fortschrittsanzeige von Parse beim Herunterladen eines XML

Ich habe es zuerst heruntergeladen, und dann Parsing, aber ich möchte beide Aktion Parallelen tun.

Dies ist Teil meines Codes, dies zu tun, aber ich weiß nicht, wie man den Pogress-Indikator zeigt.

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; 

    } 



} 

Antwort

0

Ich schlage vor, Sie verwenden AsyncTask, um zu tun, was Sie versuchen. Verwenden Sie doInBackground() zum Herunterladen und Parsen(), während Sie onProgressUpdate() zum Anzeigen des Fortschrittdialogs verwenden können. Hier ist ein Tutorial, um das Gleiche zu tun.

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

oder Sie können für AsyncTask im Android Developers Blog suchen.

EDIT

Deklarieren private ProgressDialog mProgress = null; in Ihrem erweiterten AsyncTask und fügen Sie dann die folgende Annahme Progress Parameter String und Result Parameter ist 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); 
} 

Und in Ihrem doInBackGround(), verwenden Sie die folgende Aktualisiere den Fortschrittdialog

publishProgress("your update Message"); 
+0

Sorry, dieser Code ist innerhalb meiner "doInBackground()" Methode. – lolaylo21

+0

oh toll! Dann würde der Rest sehr einfach sein, ich werde die Antwort aktualisieren – Shubhayu

+0

Ich brauche Show-Fortschritt (in%, nicht Zeichenfolge) – lolaylo21

0

Versuchen:

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); 
     } 
    } 
}