2012-06-09 42 views
0

我使用asynctask從Web服務中獲取數據。但progessdialog不顯示時,線程執行使用AsyncTask無法顯示ProgessDialog

private class Task_Bank extends AsyncTask<Void, Void, ArrayList<String>>{ 
     @Override 
     protected ArrayList<String> doInBackground(Void... params) { 
      ArrayList<String> arrayBankL = new ArrayList<String>(); 
      String url="http://qhoang.org/webservices/get_list_bank.php"; 
      JSONParser jsonParser = new JSONParser(); 
      JSONObject jsonObject = jsonParser.getJSONFromURL(url); 
      int i = 0; 
      try{ 
       JSONArray array_bank = jsonObject.getJSONArray("list_bank"); 
       for(i=0;i<array_bank.length();i++){ 
        JSONObject node = array_bank.getJSONObject(i); 
        JSONObject c = node.getJSONObject("node_list_bank"); 
        String namebank = c.getString("tennganhang"); 
        arrayBankL.add(namebank); 
       } 
      }catch(JSONException e){ 
       e.printStackTrace(); 
      } 
      return arrayBankL; 
     } 

     @Override 
     protected void onPostExecute(ArrayList<String> result) { 
      ArrayAdapter<String> arrayAdapter_bank = new ArrayAdapter<String>(TaskAActivity.this,android.R.layout.simple_spinner_item,result); 
      arrayAdapter_bank.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
      spn_bank.setAdapter(arrayAdapter_bank); 
     } 

     @Override 
     protected void onProgressUpdate(Void... values) { 
      ProgressDialog MyDialog = ProgressDialog.show(TaskAActivity.this, " " , " Loading. Please wait ... ", true); 
     } 
} 

的OnCreate()

Task_Bank a = new Task_Bank(); 
a.execute(); 

JSONParser是I類代碼使用JSON解析器從符的結果。

回答

3

您應該show()對話框onPreExecute()開始任務啓動之前,這是正確的地方。在onProgressUpdate你應該只增加你的ProgressDialog的進度。當任務onPostExecute()通話MyDialog.dismiss()

@Override 
protected void onPreExecute() { 
    progressDialog.show();   
} 

完成,以便它可以是這樣的

ProgressDialog MyDialog = ProgressDialog.show(TaskAActivity.this, " " , " Loading. Please wait ... ", true); 
// some settings 
Task_Bank a = new Task_Bank(); 
a.execute(); 

@Override 
    protected void onPreExecute() { 
     MyDialog.show();   
} 
1

你應該做一些修改代碼以顯示進度對話框。

開始顯示onPreExcecute中的ProgressDialog。

停止在onPostExcecute中顯示進度對話框。

@Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     dialog = new ProgressDialog(context); 
     dialog.setTitle("Hello"); 
     dialog.setMessage("Please Wait!!!"); 
     dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
     dialog.show(); 
    } 


@Override 
    protected void onPostExecute(Object result) { 
     dialog.dismiss(); 
       --------- 
}