0

I want to add progress bar to android project to show upload files. here is my code for upload images to server. postFile() is working fine. How to visible progress bar?

I want to add progressbar here.pleas see this code in the class

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

Here is the class

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();

        }
    }

}

Sajitha Rathnayake
  • 1,688
  • 3
  • 26
  • 47

2 Answers2

3

Add below code to your 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();
    }
}

And call this as

PostDataAsyncTask postDataAsyncTask = new PostDataAsyncTask(Youractivity_name.this);
postDataAsyncTask.execute(With_your_params);
Pankaj Kumar
  • 81,967
  • 29
  • 167
  • 186
  • Since you need Context to show dialog, keep in mind, that if your activity is closed before your AsyncTask is finished, calling dismiss() on dialog (when AsyncTask finishes) will result in exception (because your activity context is not valid anymore). To overcome this, you need to cancel your AsyncTask before your activity is finished. – hendrix Jan 22 '14 at 08:42
  • @smitalm Agreed... He is asking about to show dialog, so its clear that this task done by user not from background. Right? – Pankaj Kumar Jan 22 '14 at 08:44
  • I didnt quite understand your comment :). – hendrix Jan 22 '14 at 08:47
  • @smitalm You said about the context issue. So I am saying that this issue will come only when if Activity will be closed (Right?). Now, he is saying that he needs to show dialog, then how its possible that he is going to show dialog from background, and also he didn't say that he is finishing Activity after asynctask call.. – Pankaj Kumar Jan 22 '14 at 08:49
  • @Pankaj Kumar I try your code. I got these error Source not found. The source attachment does not contain the source of the Dialog.class. What should I do now? – Sajitha Rathnayake Jan 22 '14 at 09:11
  • @Pankaj Kumar. OK. Now its working. Thanks for all reply me to solve my problem – Sajitha Rathnayake Jan 22 '14 at 09:25
  • @Pankaj Kumar can I use mDialog.setMessage("Uploading file " + textFile); fo show current uploading file? – Sajitha Rathnayake Jan 22 '14 at 09:31
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/45774/discussion-between-pankaj-kumar-and-sajitha-rathnayake) – Pankaj Kumar Jan 22 '14 at 09:31
  • I accepted it once. But it didn't show as is. Ill do again :) – Sajitha Rathnayake Jan 22 '14 at 09:46
  • @PankajKumar Context issue shows up in this scenario: user clicks button in your application, you start AsyncTask to do some work (http request for example). While AsyncTask runs, user closes your app (or he changes orientation). Your app is closed now, but AsyncTask still runs, because its separate thread. When AsyncTask finishes, it calls dialog.dismiss() and that will throw exception, because dialog holds reference to context of activity that is no longer valid. – hendrix Jan 22 '14 at 10:19
  • @smitalm And this is not related to show dialog into AsyncTask. this is related to how we call AsyncTask into an Activity. I you have any confusion read my blog at http://pankajchunchun.wordpress.com/2012/07/27/different-implementation-of-progress-dialog-in-android/ . By the way, I am not sure if you are trying to indicate any issue in given code. – Pankaj Kumar Jan 22 '14 at 10:26
0

you can se ein this example just call progressdialog in onPreExecute() method.,and refer this example.

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();
    }
}

}

rajshree
  • 790
  • 5
  • 19