我需要在解析下载xml时显示进度指示条。
我首先下载,然后解析,但我不想做两个动作的相似之处。
这是我的代码的一部分,但我不知道如何显示pogress指标。
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;
}
}
答案 0 :(得分:0)
我建议你使用AsyncTask来做你想做的事情。使用doInBackground()下载并解析(),同时可以使用onProgressUpdate()显示progressdialog。这是一个做同样的教程。
http://www.shubhayu.com/android/witer-asynctask-what-why-how
或者您可以在Android开发者博客中搜索AsyncTask。
修改强>
在扩展的AsyncTask中声明private ProgressDialog mProgress = null;
,然后添加以下内容,假设Progress
参数为String,Result
参数为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);
}
在doInBackGround()中,使用以下命令更新progressdialog
publishProgress("your update Message");
答案 1 :(得分:0)
尝试:
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);
}
}
}