2014-01-22 52 views
0

我想添加進度條到android項目來顯示上傳文件。這裏是我的代碼上傳圖像到服務器。 postFile()工作正常。如何看到進度條?如何在Android中顯示progrssbar

我要補充進度here.pleas看到這個代碼在類

//Progrssbar Visible here      
    postFile(); 
//Progrssbar Invisible here 

這裏是類

import java.io.File; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.mime.HttpMultipartMode; 
import org.apache.http.entity.mime.MultipartEntity; 
import org.apache.http.entity.mime.content.FileBody; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.util.EntityUtils; 


import android.os.AsyncTask; 
import android.util.Log; 


public class PostDataAsyncTask extends AsyncTask<String, String, String> { 

     public String DataSendingTo="http://www.mysite.com/receiver.php/Incoming_Data_Receive"; 
     public String txtDescription; 
     public static String[] FileNameStrings = new String[8]; 

     protected void onPreExecute() { 
      super.onPreExecute(); 
      // do stuff before posting data 
     } 

     @Override 
     protected String doInBackground(String... strings) { 
      try 
      { 
       //Progrssbar Visible here      
       postFile(); 
       //Progrssbar Invisible here 

      } catch (NullPointerException e) { 

       e.printStackTrace(); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
      return null; 
     } 

     @Override 
     protected void onPostExecute(String lenghtOfFile) { 
      // do stuff after posting data 
     } 

    private void postFile(){ 
     try{ 

      // the file to be posted 
      for(int f=0;f <FileNameStrings.length;f++) 
      { 

       String textFile = FileNameStrings[f]; 
       if(textFile==null) 
       { 
        break; 
       } 

       Log.v("Sending", "textFile: " + textFile); 

       // the URL where the file will be posted 

       Log.v("Sending", "postURL: " + DataSendingTo); 

       // new HttpClient 
       HttpClient httpClient = new DefaultHttpClient(); 

       // post header 
       HttpPost httpPost = new HttpPost(DataSendingTo); 

       File file = new File(textFile); 
       FileBody fileBody = new FileBody(file); 

       MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
       reqEntity.addPart("file", fileBody); 
       httpPost.setEntity(reqEntity); 

       // execute HTTP post request 
       HttpResponse response = httpClient.execute(httpPost); 
       HttpEntity resEntity = response.getEntity(); 

       if (resEntity != null) { 

        String responseStr = EntityUtils.toString(resEntity).trim(); 
        Log.v("Sending", "Response: " + responseStr); 


        //wait(1500); 

       } 
      } 

     } catch (NullPointerException e) { 
      e.printStackTrace(); 
      //Toast.makeText(getBaseContext(), "Error:1 on uplod file", Toast.LENGTH_LONG).show(); 

     } catch (Exception e) { 
      e.printStackTrace(); 
      //Toast.makeText(getBaseContext(), "Error:2 File may be already exists", Toast.LENGTH_LONG).show(); 

     } 
    } 

}

回答

3

添加下面的代碼到你的AsyncTask

class PostDataAsyncTask extends AsyncTask<String, String, String> { 

    private ProgressDialog mDialog = null; 

    public PostDataAsyncTask(Context activityContext) { 
     mDialog = new ProgressDialog(activityContext); 
    } 

    protected void onPreExecute() { 
     super.onPreExecute(); 

     mDialog.setMessage("Wait..."); 
     mDialog.setCancelable(false); // Depends on app behaviour 
     mDialog.show(); 
    } 

    @Override 
    protected String doInBackground(String... strings) { 
     // Same as your implementation 
    } 

    @Override 
    protected void onPostExecute(String lenghtOfFile) { 
     if (mDialog != null) 
      mDialog.dismiss(); 
    } 
} 

並將其稱爲

PostDataAsyncTask postDataAsyncTask = new PostDataAsyncTask(Youractivity_name.this); 
postDataAsyncTask.execute(With_your_params); 
+0

由於需要上下文顯示對話框,請記住,如果你的活動被關閉之前你的AsyncTask完成後,調用解僱()在對話框(當的AsyncTask結束)會導致異常(因爲你的活動上下文不再有效)。爲了克服這個問題,你需要在你的活動完成之前取消你的AsyncTask。 – hendrix

+0

@smitalm同意...他要求顯示對話框,所以清楚地表明這個任務是由用戶完成的,而不是從後臺完成的。對? –

+0

我不太理解你的評論:)。 – hendrix

0

您可以在本示例中調用onPreExecute()方法中的progressdialog,並引用此示例。

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { 
/** Reference to the view which should receive the image */ 
private final WeakReference imageRef;public DownloadImageTask(ImageView imageView) { 
    imageRef = new WeakReference(imageView); 
} 

@Override 
protected void onPreExecute() { 
    super.onPreExecute(); 
    progressDialog = ProgressDialog.show(DownloadImageActivity.this, "Wait", "Downloading..."); 
} 

@Override 
protected Bitmap doInBackground(String... params) { 
    InputStream input = null; 
    try { 
     URL url = new URL(params[0]); 
     // We open the connection 
     URLConnection conection = url.openConnection(); 
     conection.connect(); 
     input = new BufferedInputStream(url.openStream(), 8192); 
     // we convert the inputStream into bitmap 
     bitmap = BitmapFactory.decodeStream(input); 
     input.close(); 
    } catch (Exception e) { 
     Log.e("Error: ", e.getMessage()); 
    } 
    return bitmap; 
} 

/** 
* After completing background task Dismiss the progress dialog 
* **/ 
protected void onPostExecute(Bitmap bitmap) { 
    progressDialog.dismiss(); 
    if (isCancelled()) { 
     bitmap = null; 
    } 

    if (imageRef != null) { 
     ImageView imageView = imageRef.get(); 
     if (imageView != null &amp;&amp; bitmap != null) { 
      imageView.setImageBitmap(bitmap); 
     } else 
      Toast.makeText(DownloadImageActivity.this, "Error while downloading the image!", Toast.LENGTH_LONG).show(); 
    } 
} 

}

+0

這個答案包含了很多冗餘的代碼,使得它很難變得有用。 – hendrix