I have a class that manages the download/upload of files to a remote service on the cloud. This class implements a listener which notifies when an operation has been finished (either a file upload/download is done, or a set of files is uploaded/downloaded).
There is a ProgressDialog created to show the progress of the operation. The progress bar is populated when the listener gets called by the download/upload manager.
The problem comes when the user turns the screen. In these case I could save the current status of the progress bar, but how can I keep the reference to the upload/download listener?
EDIT: When the user turns the screen, the progress bar is gone because the UI in the activity gets reloaded. The download/upload process continues normally until it finishes and the method "progressBar.dismiss()" is called. Then comes an exception, because the progress bar doesn't exist anymore.
SOLUTION: Follow this link to get a solution using Fragments.
UploadDownloadListener.java
public interface UploadDownloadListener {
void operationFinished(File file);
void operationFinished();
}
UploadDownloadManager.java
public void downloadAll(final UploadDownloadListener uploadDownloadListener) {
... on file downloaded ...
uploadDownloadListener.operationFinished(file);
... on all files downloaded ...
uploadDownloadListener.operationFinished();
}
MyActivity.java
public class MyActivity extends FragmentActivity {
private ProgressDialog progressBar;
private Handler progressBarbHandler = new Handler();
...
private void createAndShowProgressDialog(View view, int numberOfFiles, CharSequence title) {
Log.i(TAG, "Create progress dialog. title [" + title + "] max[" + numberOfFiles + "]");
progressBar = new ProgressDialog(view.getContext());
progressBar.setCancelable(false);
progressBar.setMessage(title);
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(numberOfFiles);
progressBar.show();
}
private class ButtonDownloadOnClickListener implements View.OnClickListener {
@Override
public void onClick(View view) {
final int numberOfFiles = getFileToDownload.size();
createAndShowProgressDialog(view, numberOfFiles, getResources().getText(R.string.label_download));
new Thread(new Runnable() {
@Override
public void run() {
uploadDownloadManager.uploadAll(getFileToDownload(), getUploadDownloadListener());
}
}).start();
}
private UploadDownloadListener getUploadDownloadListener() {
return new UploadDownloadListener() {
int item = 0;
@Override
public void operationFinished(File file) {
item++;
progressBarbHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(item);
}
});
}
@Override
public void operationFinished() {
sleep(2000);
progressBar.dismiss();
returnToMainActivity();
}
};
}