2

I would like to upload several files from my SD to a dropboxfolder. but the question is not regarding the dropbox issue:

I have a File array and I would like to upload the Files one by one, NOT ALL at the same time.

the upload works fine since I do a for loop through the File Array, but they are carried out simultaneously.

I would like to give in the progressdialog information about the total size and numbers of files

any suggestions?

thanks,

I pass from myClass:

   Log.i("toBeUploaded",
                                " " + Arrays.toString(toBeUploaded));

                        for (int i = 0; i < toBeUploaded.length; i++) {

                            Upload upload = new Upload(CalcDBActivity.this,
                                    mDBApi, getIntent().getExtras()
                                            .getString("project")
                                            + File.separatorChar,
                                    toBeUploaded[i]);
                            upload.execute();

                            if (upload.getStatus() == Upload.Status.PENDING) {
                                // My AsyncTask has not started yet
                                Log.i("Status pend",
                                        " " + upload.getStatus());
                            }

                            if (upload.getStatus() == Upload.Status.RUNNING) {
                                // My AsyncTask is currently doing work in
                                // doInBackground()
                                Log.i("Status run ",
                                        " " + upload.getStatus());
                            }

                            if (upload.getStatus() == Upload.Status.FINISHED) {
                                Log.i("Status Finished",
                                        " " + upload.getStatus());
                                // My AsyncTask is done and onPostExecute
                                // was called
                            }

                        }

where "toBeUploaded" is the file array.

the Upload Class:

public class Upload extends AsyncTask<Void, Long, Boolean> {

private DropboxAPI<?> mApi;
private String mPath;
private File mFile;

private long mFileLen;
private UploadRequest mRequest;
private Context mContext;
private final ProgressDialog mDialog;

private String mErrorMsg;


public Upload(Context context, DropboxAPI<?> api, String dropboxPath,
        File file) {
    // We set the context this way so we don't accidentally leak activities
    mContext = context.getApplicationContext();

    mFileLen = file.length();
    mApi = api;
    mPath = dropboxPath;
    mFile = file;

    mDialog = new ProgressDialog(context);
    mDialog.setMax(100);
    mDialog.setMessage("Uploading " + file.getName());
    mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mDialog.setProgress(0);
    mDialog.setButton("Cancel", new OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // This will cancel the putFile operation
            mRequest.abort();
        }
    });
    mDialog.show();
}

@Override
protected Boolean doInBackground(Void... params) {
    try {
        // By creating a request, we get a handle to the putFile operation,
        // so we can cancel it later if we want to
        FileInputStream fis = new FileInputStream(mFile);
        String path = mPath + mFile.getName();
        mRequest = mApi.putFileOverwriteRequest(path, fis, mFile.length(),
                new ProgressListener() {
            @Override
            public long progressInterval() {
                // Update the progress bar every half-second or so
                return 500;
            }

            @Override
            public void onProgress(long bytes, long total) {
                publishProgress(bytes);
            }
        });

        if (mRequest != null) {
            mRequest.upload();
            return true;
        }

    } catch (DropboxUnlinkedException e) {
        // This session wasn't authenticated properly or user unlinked
        mErrorMsg = "This app wasn't authenticated properly.";
    } catch (DropboxFileSizeException e) {
        // File size too big to upload via the API
        mErrorMsg = "This file is too big to upload";
    } catch (DropboxPartialFileException e) {
        // We canceled the operation
        mErrorMsg = "Upload canceled";
    } catch (DropboxServerException e) {
        // Server-side exception.  These are examples of what could happen,
        // but we don't do anything special with them here.
        if (e.error == DropboxServerException._401_UNAUTHORIZED) {
            // Unauthorized, so we should unlink them.  You may want to
            // automatically log the user out in this case.
        } else if (e.error == DropboxServerException._403_FORBIDDEN) {
            // Not allowed to access this
        } else if (e.error == DropboxServerException._404_NOT_FOUND) {
            // path not found (or if it was the thumbnail, can't be
            // thumbnailed)
        } else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
            // user is over quota
        } else {
            // Something else
        }
        // This gets the Dropbox error, translated into the user's language
        mErrorMsg = e.body.userError;
        if (mErrorMsg == null) {
            mErrorMsg = e.body.error;
        }
    } catch (DropboxIOException e) {
        // Happens all the time, probably want to retry automatically.
        mErrorMsg = "Network error.  Try again.";
    } catch (DropboxParseException e) {
        // Probably due to Dropbox server restarting, should retry
        mErrorMsg = "Dropbox error.  Try again.";
    } catch (DropboxException e) {
        // Unknown error
        mErrorMsg = "Unknown error.  Try again.";
    } catch (FileNotFoundException e) {
    }
    return false;
}

@Override
protected void onProgressUpdate(Long... progress) {
    int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5);
    mDialog.setProgress(percent);
}

@Override
protected void onPostExecute(Boolean result) {
    mDialog.dismiss();
    if (result) {
        showToast("Image successfully uploaded");
    } else {
        showToast(mErrorMsg);
    }
}

private void showToast(String msg) {
    Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
    error.show();
}

}

2 Answers 2

4

Move the for-loop in the main class:

Log.i("toBeUploaded", " " + Arrays.toString(toBeUploaded));

Upload upload = new Upload(CalcDBActivity.this,
    mDBApi,
    getIntent().getExtras().getString("project") + File.separatorChar,
    toBeUploaded);
upload.execute();

into the upload class:

    public class Upload extends AsyncTask<Void, Long, Boolean> {

    private DropboxAPI<?> mApi;
    private String mPath;

    private UploadRequest mRequest;
    private Context mContext;
    private ProgressDialog mDialog;

    private String mErrorMsg;

    //new class variables:
    private int mFilesUploaded;
    private File[] mFilesToUpload;
    private int mCurrentFileIndex;

    public Upload(Context context, DropboxAPI<?> api, String dropboxPath, File[] filesToUpload) {
        // We set the context this way so we don't accidentally leak activities
        mContext = context.getApplicationContext();
        mApi = api;
        mPath = dropboxPath;

        //set number of files uploaded to zero.
        mFilesUploaded = 0;
        mFilesToUpload = filesToUpload;
        mCurrentFileIndex = 0;

        mDialog = new ProgressDialog(context);
        mDialog.setMax(100);
        mDialog.setMessage("Uploading file 1 / " + filesToUpload.length);
        mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mDialog.setProgress(0);
        mDialog.setButton("Cancel", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                cancel(true);
            }
        });
        mDialog.show();
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            for (int i = 0; i < mToBeUploaded.length; i++) {
                mCurrentFileIndex = i;
                File file = mToBeUploaded[i];

                // By creating a request, we get a handle to the putFile operation,
                // so we can cancel it later if we want to
                FileInputStream fis = new FileInputStream(file);
                String path = mPath + file.getName();
                mRequest = mApi.putFileOverwriteRequest(path, fis, file.length(),
                        new ProgressListener() {
                    @Override
                    public long progressInterval() {
                         // Update the progress bar every half-second or so
                         return 500;
                    }

                    @Override
                    public void onProgress(long bytes, long total) {
                        if(isCancelled()) {
                            // This will cancel the putFile operation
                            mRequest.abort();
                        }
                        else {
                            publishProgress(bytes);
                        }
                    }
                });

                mRequest.upload();

                if(!isCancelled) {
                    mFilesUploaded++;
                }
                else {
                    return false;
                }
            }
            return true;
        } catch (DropboxUnlinkedException e) {
            // This session wasn't authenticated properly or user unlinked
            mErrorMsg = "This app wasn't authenticated properly.";
        } catch (DropboxFileSizeException e) {
            // File size too big to upload via the API
            mErrorMsg = "This file is too big to upload";
        } catch (DropboxPartialFileException e) {
            // We canceled the operation
            mErrorMsg = "Upload canceled";
        } catch (DropboxServerException e) {
            // Server-side exception.  These are examples of what could happen,
            // but we don't do anything special with them here.
            if (e.error == DropboxServerException._401_UNAUTHORIZED) {
                // Unauthorized, so we should unlink them.  You may want to
                // automatically log the user out in this case.
            } else if (e.error == DropboxServerException._403_FORBIDDEN) {
                // Not allowed to access this
            } else if (e.error == DropboxServerException._404_NOT_FOUND) {
                // path not found (or if it was the thumbnail, can't be
                // thumbnailed)
            } else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
                // user is over quota
            } else {
                // Something else
            }
            // This gets the Dropbox error, translated into the user's language
            mErrorMsg = e.body.userError;
            if (mErrorMsg == null) {
                mErrorMsg = e.body.error;
            }
        } catch (DropboxIOException e) {
            // Happens all the time, probably want to retry automatically.
            mErrorMsg = "Network error.  Try again.";
        } catch (DropboxParseException e) {
            // Probably due to Dropbox server restarting, should retry
            mErrorMsg = "Dropbox error.  Try again.";
        } catch (DropboxException e) {
            // Unknown error
            mErrorMsg = "Unknown error.  Try again.";
        } catch (FileNotFoundException e) {
        }
        return false;
    }

    @Override
    protected void onProgressUpdate(Long... progress) {
        Long totalBytes = 0;
        Long bytesUploaded = 0;
        for(int i=0;i<mFilesToUpload.length;i++) {
            Long bytes = mFilesToUpload[i].length()
            totalBytes += bytes;

            if(i < mCurrentFileIndex) {
                bytesUploaded += bytes;
            }
        }
        bytesUploaded += progress[0];

        mDialog.setMessage("Uploading file " + (mCurrentFileIndex+1) + " / " + filesToUpload.length);
        mDialog.setProgress((bytesUploaded / totalBytes) * 100);
    }

    @Override
    protected void onPostExecute(Boolean result) {
        mDialog.dismiss();
        if (result) {
            showToast("Image successfully uploaded");
        } else {
            showToast(mErrorMsg);
        }
    }

    private void showToast(String msg) {
        Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
        error.show();
    }
}
Sign up to request clarification or add additional context in comments.

10 Comments

Hello, I got a little stucked here. I created the class "FileToUpload" and eclipse made me remove the Override of "public void onProgress(long bytes, long total)" and "public long progressInterval()" and implemented "@Override public void onProgress(int progress)" I can pass the fileList to my Upload class. can You please alter my Upload class with Your 2nd part of the code? I am a newbie on that
I removed my special class so that you have less changes to do. It should now be easier to understand.
Thanks Daverix, I tested your snippet and it works fine! the counter is updated but the progressbar is not updating only for the last bar. Can You check if there is something wrong?
I checked it with the dropboxfolder. first there is a dialog shown showing "Uploading file 1 / eg. 7" in this dialog ALL files are uploaded, afterwards the dialog is beginning to change 1/7!!, 2/7, 3/7 and so on. the progressbar is only updated in the last (7/7) dialog
I unaccept in order to notify that there is still a problem and to keep the discussion alive. Anny suggestions?
|
1

With the help of Daverix, I managed to get to an solution I post the code below, just in case someone has the same problem with progressbars.

I changed the name of some variables compared to the earlier versions:

public class Upload extends AsyncTask<Void, Long, Boolean> {

private DropboxAPI<?> mApi;
private String mPath;

private UploadRequest mRequest;
private Context mContext;
private ProgressDialog mDialog;

private String mErrorMsg,filename;

// new class variables:
private int mFilesUploaded;
private File[] mFilesToUpload;
private int mCurrentFileIndex;

int totalBytes = 0, indBytes = 0;

public Upload(Context context, DropboxAPI<?> api, String dropboxPath,
        File[] filesToUpload) {
    // We set the context this way so we don't accidentally leak activities
    mContext = context.getApplicationContext();
    mApi = api;
    mPath = dropboxPath;

    // set number of files uploaded to zero.
    mFilesUploaded = 0;
    mFilesToUpload = filesToUpload;
    mCurrentFileIndex = 0;

    for (int i = 0; i < mFilesToUpload.length; i++) {
        Long bytes = mFilesToUpload[i].length();
        totalBytes += bytes;
    }

    mDialog = new ProgressDialog(context);
    mDialog.setMax(100);
    mDialog.setMessage("Uploading file 1 / " + filesToUpload.length);
    mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mDialog.setProgress(0);
    mDialog.setButton("Cancel", new OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            cancel(true);
        }
    });
    mDialog.show();
}

@Override
protected Boolean doInBackground(Void... params) {
    try {
        for (int i = 0; i < mFilesToUpload.length; i++) {
            mCurrentFileIndex = i;
            File file = mFilesToUpload[i];

            int bytes = (int) mFilesToUpload[i].length();
            indBytes = bytes;

            filename= mFilesToUpload[i].getName();


            // By creating a request, we get a handle to the putFile
            // operation,
            // so we can cancel it later if we want to
            FileInputStream fis = new FileInputStream(file);
            String path = mPath + file.getName();
            mRequest = mApi.putFileOverwriteRequest(path, fis,
                    file.length(), new ProgressListener() {
                        @Override
                        public long progressInterval() {
                            // Update the progress bar every half-second or
                            // so
                            return 100;
                        }

                        @Override
                        public void onProgress(long bytes, long total) {
                            if (isCancelled()) {
                                // This will cancel the putFile operation
                                mRequest.abort();
                            } else {
                                publishProgress(bytes);
                            }
                        }
                    });

            mRequest.upload();

            if (!isCancelled()) {
                mFilesUploaded++;
            } else {
                return false;
            }
        }
        return true;
    } catch (DropboxUnlinkedException e) {
        // This session wasn't authenticated properly or user unlinked
        mErrorMsg = "This app wasn't authenticated properly.";
    } catch (DropboxFileSizeException e) {
        // File size too big to upload via the API
        mErrorMsg = "This file is too big to upload";
    } catch (DropboxPartialFileException e) {
        // We canceled the operation
        mErrorMsg = "Upload canceled";
    } catch (DropboxServerException e) {
        // Server-side exception. These are examples of what could happen,
        // but we don't do anything special with them here.
        if (e.error == DropboxServerException._401_UNAUTHORIZED) {
            // Unauthorized, so we should unlink them. You may want to
            // automatically log the user out in this case.
        } else if (e.error == DropboxServerException._403_FORBIDDEN) {
            // Not allowed to access this
        } else if (e.error == DropboxServerException._404_NOT_FOUND) {
            // path not found (or if it was the thumbnail, can't be
            // thumbnailed)
        } else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
            // user is over quota
        } else {
            // Something else
        }
        // This gets the Dropbox error, translated into the user's language
        mErrorMsg = e.body.userError;
        if (mErrorMsg == null) {
            mErrorMsg = e.body.error;
        }
    } catch (DropboxIOException e) {
        // Happens all the time, probably want to retry automatically.
        mErrorMsg = "Network error.  Try again.";
    } catch (DropboxParseException e) {
        // Probably due to Dropbox server restarting, should retry
        mErrorMsg = "Dropbox error.  Try again.";
    } catch (DropboxException e) {
        // Unknown error
        mErrorMsg = "Unknown error.  Try again.";
    } catch (FileNotFoundException e) {
    }
    return false;
}

@Override
protected void onProgressUpdate(Long... progress) {

    mDialog.setMessage("Uploading file " + (mCurrentFileIndex + 1) + " / "
            + mFilesToUpload.length+"\n"+filename);
    int percent = (int) (100.0 * (double) progress[0] / indBytes + 0.5);
    Log.i("pro", percent + "    " + progress[0] + "/" + indBytes);
    mDialog.setProgress(percent);
}

@Override
protected void onPostExecute(Boolean result) {
    mDialog.dismiss();
    if (result) {
        showToast("Upload finished");
    } else {
        showToast(mErrorMsg);
    }
}

private void showToast(String msg) {
    Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
    error.show();
}
}

2 Comments

I thought you wanted a progressbar for all files, but I can see that you only wanted to see status of the current file uploading?
What about having a progress bar for all files?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.