Properly set upload progress on image
<p>I was trying to go about setting a progress bar dialog for uploading an image to my server via AsyncTask. I have the below code but as you could guess it doesn't work as I would want. I want to have accurate % being shown for the upload progress of the image, and I hope I can get some guidance as to how to do this properly. Thank you again.</p>

<pre><code>public class ImageUploader extends AsyncTask &lt;String, Integer, String&gt;{
Context ctx;
ProgressDialog dialog;

public ImageUploader(Context context){
    this.ctx = context;
    this.dialog = new ProgressDialog(ctx);
}

@Override
protected void onPreExecute() {
    dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    dialog.setMax(100);
    dialog.setProgress(0);
    dialog.show();
    super.onPreExecute();
}

@Override
protected String doInBackground(String... params) {
    ArrayList&lt;NameValuePair&gt; nameValuePairs = null;
    StringBuilder sb = null;

    int bufferLength = 1024;



       try{
           Bitmap bitmapOrg = BitmapFactory.decodeFile(params[0]);


            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
            byte [] ba = bao.toByteArray();

            String ba1 = Base64.encodeToString(ba, Base64.DEFAULT);
           for (int i = 0; i &lt; ba.length; i+= bufferLength) {

               publishProgress((int) ((i / (float) ba.length) * 100));

           }

            nameValuePairs = new ArrayList&lt;NameValuePair&gt;();
            nameValuePairs.add(new BasicNameValuePair("image",ba1));
            nameValuePairs.add(new BasicNameValuePair("user",String.valueOf(1)));
       }catch (Exception e){Log.i("IMAGE CONVERT FAIL", e.getMessage());}

        try{

            HttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost("url.php");

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpclient.execute(httppost);

            HttpEntity entity = response.getEntity();

            InputStream is = entity.getContent();

            sb = new StringBuilder();
            sb.append(is.read());

            is.close();
        }catch(Exception e){
            Log.e("Uploader http error", "Error in http connection "+e.toString());
            return null;
        }

    return sb.toString();
}

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

@Override
protected void onPostExecute(String sResponse) {
    try {
       if (dialog.isShowing())
           dialog.dismiss();


               Log.i("UPLOADER LOG", sResponse);

    } catch (Exception e) {
        Log.e(e.getClass().getName(), e.getMessage(), e);
    }
}
</code></pre>
