brian
brian

Reputation: 6912

How to get the upload progress

I use doInBackGround and AsyncTask method to show progress as below:

class UploadFile extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

    @Override
    protected String doInBackground(String... aurl) {
        upload(ActionUrl, uploadFile, savepath, newName);
        return null;
    }

    protected void onProgressUpdate(String... progress) {
        mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String unused) {
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
    }
}

The upload(ActionUrl, uploadFile, savepath, newName); method is such as this. And below code:

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS: //we set this to 0
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Downloading file...");
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.setMax(100);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(true);
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
    }
}

And below to call:

private ProgressDialog mProgressDialog;
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
new UploadFile().execute("test");

But the Progress Dialog always show 0%, and never update. How to modify to update it?

Upvotes: 1

Views: 670

Answers (2)

Squonk
Squonk

Reputation: 48871

You have to call publishProgress(...) in your doInBackground(...) method. It's what causes onProgressUpdate(...) to be called. The onProgressUpdate(...) isn't called magically.

It's designed to be multi-purpose and it's your responsibility to trigger it through publishProgress(...) with whatever 'progress' data you want it to publish. It can be numeric such as 10 for 10 percent or a string such as First file downloaded....

The AsyncTask class has no idea what you want to publish or when - that's what a call to publishProgress(...) from doInBackground(...) is meant to do.

Upvotes: 1

Viking
Viking

Reputation: 866

you will need to create the second thread which will track the progress and report it to this activity.Here is the link which has an example on how to accomplish this: http://developer.android.com/guide/topics/ui/dialogs.html

In this link look for "Example ProgressDialog with a second thread"

Upvotes: 1

Related Questions