2012-09-26 25 views
9

Ho un task asincrono che non aggiunge la percentuale mentre sta attraversando l'attività. Rimane sempre a 0% 0/100Imposta avanzamento della finestra di dialogo

Ecco il mio codice

 private class getAppInfo extends AsyncTask<String, String, String> { 
    /** The system calls this to perform work in a worker thread and 
     * delivers it the parameters given to AsyncTask.execute() */ 
    ProgressDialog dialog; 

    @Override 
    protected void onPreExecute() { 
     if(showLoading == true){ 
      dialog = new ProgressDialog(SelfHelp.this); 
      dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
      dialog.setMessage("Loading"); 
      dialog.setIndeterminate(true); 
      dialog.setCancelable(false); 
      dialog.setMax(100); 
      dialog.setProgress(100); 
      dialog.show(); 
     } 
    } 

    @Override 
    protected String doInBackground(String... urls) {      
     String xml = null; 
     int count = 0; 
     try { 
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpGet httpGet = new HttpGet(urls[0]); 

      HttpResponse httpResponse = httpClient.execute(httpGet); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      xml = EntityUtils.toString(httpEntity); 

      while(count != 100){ 
       publishProgress(""+count); 
       count += 5; 
      } 

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     }         

     Document doc = parser.GetDomElement(xml); 
     NodeList nl = doc.getElementsByTagName("topic"); 
     getChildElements(nl);       
     return xml; 
    } 


    @Override 
    protected void onProgressUpdate(String... progress) { 
     Log.v("count",progress[0]); 
     dialog.setProgress(Integer.parseInt(progress[0])); 
    } 

    /** The system calls this to perform work in the UI thread and delivers 
     * the result from doInBackground() */ 
    @Override 
    protected void onPostExecute(String result) {  
     //dialog.setProgress(100); 
     menuList.setAdapter(setListItems(menuItems)); 
     menuList.setTextFilterEnabled(true); 
     if(showLoading == true){ 
      dialog.dismiss(); 
      showLoading = false; 
     } 
    } 

Non andare in onProgressUpdate e il conteggio va da 5 ma la barra di avanzamento non cambia. Come posso farlo incrementare per 5 e mostrare il progresso correttamente?

risposta

26

Il tuo problema è collegato a setIndeterminate(true): È necessario impostarlo su false se si desidera avere l'aggiornamento di avanzamento. se si setIndeterminate(true) poi il ProgressDialog funzionerà come il classico di Windows Clessidra

+0

Questo suggerimento non ha cambiato nulla. Non è stato ancora spostato oltre lo 0% – BigT

+0

set dialog.setProgress (100); a 0 invece di 100 – Blackbelt

+0

l'impostazione del progresso nel preExecute su 0 non ha funzionato ancora – BigT

3

Si può provare seguente codice, si sta mostrando progressi nel rapporto%, ecco il codice,

public class ProgressBarExampleActivity extends Activity 
{ 
    ProgressThread progThread; 
    ProgressDialog progDialog; 
    Button button1, button2; 
    int typeBar;      // Determines type progress bar: 0 = spinner, 1 = horizontal 
    int delay = 1000;     // Milliseconds of delay in the update loop 
    int maxBarValue = 30;   // Maximum value of horizontal progress bar 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

//  // Process button to start spinner progress dialog with anonymous inner class 
//  button1 = (Button) findViewById(R.id.Button01); 
//  button1.setOnClickListener(new OnClickListener() 
//  { 
//   public void onClick(View v) 
//   { 
//    typeBar = 0; 
//    showDialog(typeBar); 
//   } 
//  }); 

     // Process button to start horizontal progress bar dialog with anonymous inner class 
     button2 = (Button) findViewById(R.id.Button02); 
     button2.setOnClickListener(new OnClickListener() 
     { 
      public void onClick(View v) 
      { 
       typeBar = 1; 
       showDialog(typeBar); 
      } 
     }); 
    } 

    // Method to create a progress bar dialog of either spinner or horizontal type 
    @Override 
    protected Dialog onCreateDialog(int id) 
    { 
     switch(id) 
     { 
//  case 0:      // Spinner 
//   progDialog = new ProgressDialog(this); 
//   progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
//   progDialog.setMessage("Loading..."); 
//   progThread = new ProgressThread(handler); 
//   progThread.start(); 
//   return progDialog; 
     case 1:      // Horizontal 
      progDialog = new ProgressDialog(this); 
      progDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
      progDialog.setMax(maxBarValue); 
      progDialog.setMessage("Dollars in checking account:"); 
      progThread = new ProgressThread(handler); 
      progThread.start(); 
      return progDialog; 
     default: 
      return null; 
     } 
    } 

    // Handler on the main (UI) thread that will receive messages from the 
    // second thread and update the progress. 

    final Handler handler = new Handler() 
    { 
     public void handleMessage(Message msg) 
     { 
      // Get the current value of the variable total from the message data 
      // and update the progress bar. 
      int total = msg.getData().getInt("total"); 
      progDialog.setProgress(total); 
//   if (total >= maxBarValue) 
      if (total <= 0)    
      { 
       dismissDialog(typeBar); 
       progThread.setState(ProgressThread.DONE); 
      } 
     } 
    }; 

    // Inner class that performs progress calculations on a second thread. Implement 
    // the thread by subclassing Thread and overriding its run() method. Also provide 
    // a setState(state) method to stop the thread gracefully. 

    private class ProgressThread extends Thread 
    { 
     // Class constants defining state of the thread 
     final static int DONE = 0; 
     final static int RUNNING = 1; 

     Handler mHandler; 
     int mState; 
     int total; 

     // Constructor with an argument that specifies Handler on main thread 
     // to which messages will be sent by this thread. 

     ProgressThread(Handler h) 
     { 
      mHandler = h; 
     } 

     // Override the run() method that will be invoked automatically when 
     // the Thread starts. Do the work required to update the progress bar on this 
     // thread but send a message to the Handler on the main UI thread to actually 
     // change the visual representation of the progress. In this example we count 
     // the index total down to zero, so the horizontal progress bar will start full and 
     // count down. 

     @Override 
     public void run() 
     { 
      mState = RUNNING; 
      total = maxBarValue; 
      while (mState == RUNNING) 
      { 
       // The method Thread.sleep throws an InterruptedException if Thread.interrupt() 
       // were to be issued while thread is sleeping; the exception must be caught. 
       try 
       { 
        // Control speed of update (but precision of delay not guaranteed) 
        Thread.sleep(delay); 
       } catch (InterruptedException e) { 
        Log.e("ERROR", "Thread was Interrupted"); 
       } 

       // Send message (with current value of total as data) to Handler on UI thread 
       // so that it can update the progress bar. 

       Message msg = mHandler.obtainMessage(); 
       Bundle b = new Bundle(); 
       b.putInt("total", total); 
       msg.setData(b); 
       mHandler.sendMessage(msg); 

       total--; // Count down 
      } 
     } 

     // Set current state of thread (use state=ProgressThread.DONE to stop thread) 
     public void setState(int state) 
     { 
      mState = state; 
     } 
    } 
} 

Vedere l'uscita,

enter image description here

1

Accennerò a un altro approccio, perché ho trovato questa soluzione quando stavo cercando un modo pratico per comunicare dal mio servizio eseguendo AsyncTask sull'interfaccia utente principale. La soluzione di Lucifer non è modulare per i servizi, se hai bisogno di utilizzare il tuo servizio in più di 1 classe (era il mio caso), non sarai in grado di accedere al gestore di variabili e per quanto ne so non puoi nemmeno inviare Handler come Intent to Service (puoi inviarlo a AsyncTask tho). La soluzione sta trasmettendo.

sendBroadcast(new Intent(WORK_DONE)); 

in AsyncTask e

private BroadcastReceiver receiver = new BroadcastReceiver() { 
    public void onReceive(Context c, Intent i) { //update your UI here } 
} 

registerReceiver(receiver, new IntentFilter(WORK_DONE)); 

nella vostra attività.

Non mi piacciono tutte quelle classi interne che gli sviluppatori Android usano. Capisco che sia più facile creare classi interne e accedere a variabili di classe esterne, ma una volta che hai bisogno di usare di nuovo la classe, sei condannato e devi modificare il codice! Sono davvero nuovo per Android, forse ho torto e in realtà non è necessario riutilizzare quelle classi. Non ho mai fatto un progetto più grande, quindi non ne ho idea, ma non mi sembra giusto, dal momento che al college, hanno provato a insegnarci come programmare il codice riutilizzabile.

Problemi correlati