2011-12-30 101 views
0

我在圖片上傳過程中遇到了一些問題,無法正確顯示ProgressDialog。 我在AsynkTask中創建了HTTPRequest,並使用doInBackground()和progressUpdate()方法更新了進度條,但出現了一些問題。當我從主要活動開始任務時,ProgressDialog不會啓動,但僅在上傳結束後才顯示。圖片上傳期間的ProgressDialog無法正確顯示

這裏是工作的代碼:

public class HTTPReqPostTask extends AsyncTask<Void, Integer, String> 
{ 
private funzioni func = new funzioni(); 
private static final String TAG = "MotoRnUpload"; 
private ProgressBar progress; 
private final Foto img; 
private final Album al; 
private final URL endpoint; 
private String result; 
private byte[] bytes; 
private ProgressDialog dialog; 
private Activity parent; 

public HTTPReqPostTask(Activity act,final Foto f,final Album a,final URL u){ 
    parent = act; 
    img = f; 
    al = a; 
    endpoint = u; 
    result = null; 
    bytes = func.imgToBytes2(img);   
} 

@Override 
protected void onPreExecute() { 
    dialog = new ProgressDialog(parent); 
    dialog.setMessage("Uploading..."); 
    dialog.setIndeterminate(false); 
    dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
    dialog.setProgress(0);   
    dialog.show();   
} 

/* 
* 
*/ 
@Override 
protected String doInBackground(final Void... args) 
{ 
final String CrLf = "\r\n"; 

int i=0,w,h; 
HttpURLConnection urlc = null; 
DataOutputStream printout; 
Bitmap b_img = BitmapFactory.decodeFile((img.getFile()).getAbsolutePath()); 

w = b_img.getWidth(); 
h = b_img.getHeight(); 

if(img.getRotationL() == 1 || img.getRotationR() == 1){ 
     int dim; 
     dim = w; 
     w = h; 
     h = dim; 
} 

String message1="",message2="",message3="",message4="",message5="",message6="",message7="",message8="", 
       message9="",message10="",message11="",message12="",message14=""; 
try 
{ 
     urlc = (HttpURLConnection) endpoint.openConnection(); 
     try 
     { 
       urlc.setRequestMethod("POST"); 
       urlc.setRequestProperty("Connection", "Keep-Alive"); 
     } catch (ProtocolException e) 
       { 
        Log.e(TAG, e.getMessage(),e.fillInStackTrace()); 
       } 
     urlc.setDoOutput(true); 
     urlc.setDoInput(true); 
     urlc.setUseCaches(false); 
     urlc.setAllowUserInteraction(false); 

     message1 += "-----------------------------4664151417711" + CrLf; 
     message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test"+bytes.length+".jpg\"" + CrLf; 
     message1 += "Content-Type: image/jpeg" + CrLf; 
     message1 += CrLf; 
     // the image is sent between the messages in the multipart message. 
     message2 += CrLf + "-----------------------------4664151417711--" + CrLf; 
     //dati normali 
     message3 += "-----------------------------4664151417711" + CrLf; 
     message3 += "Content-Disposition: form-data; name=\"nomeFoto\"" + CrLf +CrLf; 
     // 
     message4 += "-----------------------------4664151417711" + CrLf; 
     message4 += "Content-Disposition: form-data; name=\"idCat\"" + CrLf +CrLf; 
     // 
     message5 += "-----------------------------4664151417711" + CrLf; 
     message5 += "Content-Disposition: form-data; name=\"idAlbum\"" + CrLf +CrLf; 
     // 
     message6 += "-----------------------------4664151417711" + CrLf; 
     message6 += "Content-Disposition: form-data; name=\"nomeAlbum\"" + CrLf +CrLf; 
     // 
     message7 += "-----------------------------4664151417711" + CrLf; 
     message7 += "Content-Disposition: form-data; name=\"idUser\"" + CrLf +CrLf; 
     // 
     message8 += "-----------------------------4664151417711" + CrLf; 
     message8 += "Content-Disposition: form-data; name=\"isPrivato\"" + CrLf +CrLf; 
     // 
     message9 += "-----------------------------4664151417711" + CrLf; 
     message9 += "Content-Disposition: form-data; name=\"isNew\"" + CrLf +CrLf; 
     // 
     message10 += "-----------------------------4664151417711" + CrLf; 
     message10 += "Content-Disposition: form-data; name=\"width\"" + CrLf +CrLf; 
     // 
     message11 += "-----------------------------4664151417711" + CrLf; 
     message11 += "Content-Disposition: form-data; name=\"height\"" + CrLf +CrLf; 
     // 
     message12 += "-----------------------------4664151417711" + CrLf; 
     message12 += "Content-Disposition: form-data; name=\"gps_lat\"" + CrLf +CrLf; 
     // 
     message14 += "-----------------------------4664151417711" + CrLf; 
     message14 += "Content-Disposition: form-data; name=\"gps_lon\"" + CrLf +CrLf; 
     // 
     urlc.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------4664151417711"); 
     // might not need to specify the content-length when sending chunked data. 
     //urlc.setRequestProperty("Content-Length", String.valueOf((message1.length() + String.valueOf(message2.length()) + String.valueOf(bytes.length)))); 


     printout = new DataOutputStream (urlc.getOutputStream()); 
     // 
     // invia il nome del file 
     // 
     printout.write(message3.getBytes()); 
     printout.writeBytes(img.getNome()); 
     printout.writeBytes(CrLf); 
     // 
     printout.write(message10.getBytes()); 
     printout.writeBytes(Integer.toString(w)); 
     printout.writeBytes(CrLf); 
     // 
     printout.write(message11.getBytes()); 
     printout.writeBytes(Integer.toString(h)); 
     printout.writeBytes(CrLf); 
     // 
     printout.write(message7.getBytes()); 
     printout.writeBytes(Integer.toString(img.getIdUser())); 
     printout.writeBytes(CrLf); 
     // 
     printout.write(message9.getBytes()); 
     printout.writeBytes(Boolean.toString(al.isNew())); 
     printout.writeBytes(CrLf); 
     // 
     if(img.hasGps()){ 
       printout.write(message12.getBytes()); 
       printout.writeBytes(img.getGpsLat()); 
       printout.writeBytes(CrLf); 
       // 
       printout.write(message14.getBytes()); 
       printout.writeBytes(img.getGpsLon()); 
       printout.writeBytes(CrLf); 
       // 
     } 
     // 
     if(al.isNew()){ 
       printout.write(message4.getBytes()); 
       printout.writeBytes(Integer.toString(al.getIdCat())); 
       printout.writeBytes(CrLf); 
       // 
       printout.write(message6.getBytes()); 
       printout.writeBytes(al.getNome()); 
       printout.writeBytes(CrLf); 
       // 
       printout.write(message8.getBytes()); 
       printout.writeBytes(Boolean.toString(al.isPrivato())); 
       printout.writeBytes(CrLf); 
     }else{ 
       printout.write(message5.getBytes()); 
       printout.writeBytes(Integer.toString(al.getId())); 
       printout.writeBytes(CrLf); 
     } 
     // 
     // invia la foto 
     // 
     printout.write(message1.getBytes()); 

     // SEND THE IMAGE 
     int size = 1024;  
     do{   
      publishProgress(i); 
      if((i+size)>bytes.length){ 
       size = bytes.length - i; 
      } 
      printout.write(bytes, i, size); 
      i+=size;     
     }while(i<bytes.length); 
     publishProgress(bytes.length); 
     // 
     printout.write(message2.getBytes()); 
     printout.flush(); 
     printout.close(); 
     Log.i(TAG, "Immagine inviata");    
     //Get the response 
     BufferedReader rd = new BufferedReader(new InputStreamReader(urlc.getInputStream())); 
     StringBuffer sb = new StringBuffer(); 
     String line; 
     while ((line = rd.readLine()) != null) 
     { 
      sb.append(line); 
     } 
     rd.close(); 
     result = sb.toString(); 
} catch (Exception e) 
{ 
    Log.e(TAG,e.toString(),e.fillInStackTrace()); 
} 
return result; 
} 

@Override 
protected void onProgressUpdate(final Integer... values) { 
    dialog.setProgress(values[0]); 
} 

@Override 
protected void onPostExecute(final String res) { 
    dialog.dismiss(); 
} 
} 

這是代碼調用,在主Activity類任務的一部分:

public void onClick(View view) { 
    if(view.getId() == R.id.button1){ 
     try{ 
      String result; 
      JSONObject info_upload; 
      result = new HTTPReqPostTask(MainActivity.this,foto,alb,new    URL(urlUpload)).execute().get(); 
      info_upload = new JSONObject(result); 
      if(info_upload.getString("stato").equals("fail")){ 
       funzioni.popUp(MainActivity.this,"Errore caricamento foto: "+info_upload.getString("info"));      
      }else{ 
       funzioni.popUp(MainActivity.this,"Foto caricata correttamente su MotoRn"); 
       if(info_upload.getString("stato").equals("create")){ 
        alb.setId(info_upload.getInt("id_album")); 
        alb.setIsNew(false); 
       } 
      } 
     }catch(MalformedURLException mue){ 
      Log.e(TAG,mue.toString(),mue.fillInStackTrace()); 
      funzioni.popUp(MainActivity.this, mue.getMessage()+" : "+mue.getLocalizedMessage()); 
     }catch(Exception e){ 
      Log.e(TAG,e.toString(),e.fillInStackTrace()); 
      funzioni.popUp(MainActivity.this, e.getMessage()+" : "+e.getLocalizedMessage()); 
     } 
    }else if(view.getId() == R.id.b_open){ 
     startActivityForResult(new Intent(Intent.ACTION_PICK, 
      android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI), SELECT_IMAGE_CODE); 
    } 
} 

感謝您的支持;)

+1

你見過http://stackoverflow.com/questions/2702695/android-async-task-progressdialog-isnt-showing-until-background-thread-finishes?嘗試硬編碼上下文,而不是使用你在構造函數中傳遞的內容(dialog = new ProgressDialog(MyClass.this)或dialog = new ProgressDialog(getApplicationContext()))也許? – Jack 2011-12-30 17:37:01

+0

已經完成但沒有任何改變。如果我使用getApplicationContext(),我得到錯誤「無法添加窗口 - 標記null不適用於應用程序」。我讀過你告訴我的帖子,但這並沒有解決我的問題。 – 2011-12-30 18:13:56

回答

0

嘗試在當時傳遞真實的上下文,我相信你正試圖將異步任務的結果傳遞給字符串變量「result」。主線程必須等到異步任務完成後才掛起,因此無法顯示對話框。

+0

是的,我認爲這是問題所在。我該如何解決這個問題?我應該在單獨的線程中執行asyncTask嗎?謝謝你的回答;) – 2011-12-30 18:45:26

+0

異步任務已經是另一個線程了。 onPre和onPost方法在主線程上運行,onBackG在單獨的線程上運行。你不能在第二次開始任務時使用結果,你必須以某種方式編碼它可以稍後再回來,這就是它的重點。 – NikkyD 2011-12-30 18:58:15

+0

好吧,我解決了不使用結果,但現在我已經弄清楚如何以其他方式獲得結果。感謝您的建議;) – 2011-12-30 21:41:09