3

How should I be using AsyncTask class coupled with a progress bar to perform the copying process of a file to another directory in the local context of the phone sdcard? I have seen a similar example [here][1], but I have no idea how to incorporate the differences/modify the context of the code to suit my context to make it work?

peterh
  • 11,875
  • 18
  • 85
  • 108
Vivian
  • 1,071
  • 5
  • 16
  • 29

2 Answers2

7

It would be something like

// Params are input and output files, progress in Long size of 
// data transferred, Result is Boolean success.
public class MyTask extends AsyncTask<File,Long,Boolean> {
   ProgressDialog progress; 

  @Override
  protected void onPreExecute() {
    progress = ProgressDialog.show(ctx,"","Loading...",true);
  }

  @Override
  protected Boolean doInBackground(File... files) {
    copyFiles(files[0],files[1]);
    return true;
  }

  @Override
  protected void onPostExecute(Boolean success) {
    progress.dismiss();
    // Show dialog with result
  }

  @Override
  protected void onProgressUpdate(Long... values) {
    progress.setMessage("Transferred " + values[0] + " bytes");
  }
}

Now, inside copyFiles you will have to call publishProgress() with size of data transferred, for example. Note that progress generic parameter is Long. You can use CountingInputStream wrapper from commons-io for that.

There are number of additional things top take care of, but in the nutshell that is it.

To start:

  MyTask task = new MyTask();
  task.execute(src,dest);
Sergii
  • 1,521
  • 3
  • 24
  • 37
Alex Gitelman
  • 24,429
  • 7
  • 52
  • 49
  • @Alex Gitelman thanks for your help but can you check my newly updated answers yet another problem above pertaining to the aftermath of copying the file to the desired directory? – Vivian May 19 '11 at 15:05
  • @Alex Gitelman And by the way my AsyncTask progress bar does not seems to work the way it intended as it should according to your code?? Have i missed something else in my code therefore it lacks the proper of functionality while running the code? sorry i'm rather quite new to android programming... – Vivian May 19 '11 at 15:14
  • @Vivian I don't understand your question about 'can you check my newly updated answers yet another problem'. I'd be happy to help but please be more specific. Is it related to this question? Secondly, clarify 'progress bar does not seems to work the way it intended'. The sample I provided, sets progress bar to be indeterminate so it shows rotating circle. If that's the problem I will add another snippet to my answer to fix it. – Alex Gitelman May 19 '11 at 16:34
  • @Alex Gitelman apart from the rotating circle why is does not seems to have the message "progress.setMessage("Transferred " + values[0] + " bytes");" shouldn't it be set while transferring the file? Correct me for my understanding if i'm wrong.. I do have another question slightly related to the problem arise after copying the file --> http://stackoverflow.com/questions/6060982/why-is-the-content-of-my-listview-entries-not-updated-after-the-transfer-of-file – Vivian May 20 '11 at 00:55
  • @Vivian did you call publishProgress() as described from copyFiles()? Initially it will say 'Loading'. I coded something similar yesterday and it worked for me. – Alex Gitelman May 20 '11 at 01:03
  • @Alex Gitelman getting lost from my coding... Sorry rather new in programming – Vivian May 20 '11 at 01:07
  • @Alex Gitelman don't quite understand what you mean? "progress.setMessage("Transferred " + values[0] + " bytes");" because i was wondering why this line here is not being called or seen on the screen? – Vivian May 20 '11 at 01:10
  • you have to call publishProgress method on your AsyncTask during file copy. How otherwise it will know what values to put in message? You can't call onProgressUpdate() directly and you can't update progress from copy method because it must happen on UI thread. So you call publishProgress() and AsyncTask takes care of passing your data to onProgressUpdate but on UI thread as required. And don't worry about experience - we all've been there. Just keep doing it and it will come. How ever try to explore as much as possible on your own. – Alex Gitelman May 20 '11 at 01:23
  • @Alex Gitelman sorry for yet asking again for the repeated question.. i've updated my answer but it still can't work? – Vivian May 20 '11 at 01:37
  • @Alex Gitelman "progress.setMessage("Transferred " + values[0] + " bytes");" error here? – Vivian May 20 '11 at 01:42
  • @Alex Gitelman it will only work when i have it as progress.setMessage("Transferred " + values + " bytes") lol but not is its not updating my listview content here --> http://stackoverflow.com/questions/6060982/why-is-the-content-of-my-listview-entries-not-updated-after-the-transfer-of-file – Vivian May 20 '11 at 01:54
  • @Vivian I think that you called publishProgress() with no parameters. As a result you get array of 0 length and ArrayIndexOutOfBoundsException when you try to get element 0. Call publishProgress with specific value of number of bytes transferred (or whatever you choose). So publishProgress(bytesTransferred); – Alex Gitelman May 20 '11 at 02:06
  • @Alex Gitelman can you take a look with another of my problem here --> http://stackoverflow.com/questions/6060567/how-to-enable-autoplay-of-video-in-sequences-upon-selection-in-a-listview – Vivian May 20 '11 at 04:33
  • @Vivian I don't know enough about the subject of other question to answer it. – Alex Gitelman May 20 '11 at 05:50
  • @Alex Gitelman sorry to raise the question again. but can i ask how can i use the above to delete a file instead? when i run your code to delete file it doesn't work? Can should i do to your code to make it work? Could you update your code to let me see how it should delete a file with progressbar? – Vivian May 22 '11 at 15:55
1

Try using Async task as shown below:

 try{
    class test extends AsyncTask{


         TextView tv_per;
         int mprogress;

        Dialog UpdateDialog = new Dialog(ClassContext);

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            mprogress = 0;

            UpdateDialog.setTitle(getResources().getString(R.string.app_name));
            UpdateDialog.setContentView(R.layout.horizontalprogressdialog);
            TextView dialog_message =  (TextView)UpdateDialog.findViewById(R.id.titleTvLeft);
            tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
            dialog_message.setText(getResources().getString(R.string.dialog_retrieving_data));
            dialog_message.setGravity(Gravity.RIGHT);
            UpdateDialog.setCancelable(false);
            UpdateDialog.show();
            super.onPreExecute();
        }



        @Override
        protected void onProgressUpdate(Object... values) {
            // TODO Auto-generated method stub
            ProgressBar update = (ProgressBar)UpdateDialog.findViewById(R.id.horizontalProgressBar);
            update.setProgress((Integer) values[0]);
            int percent =  (Integer) values[0];
            if(percent>=100)
            {
                percent=100;
            }
            tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
             tv_per.setText(""+percent);
        }



        @Override
        protected Object doInBackground(Object... params) {
            // TODO Auto-generated method stub
            //your code
}

            super.onPostExecute(result);
            UpdateDialog.dismiss();
        }

     }
     new test().execute(null);

 }
 catch(Exception e)
 {
     e.printStackTrace();
 }
Jaydeep Khamar
  • 5,975
  • 3
  • 32
  • 30
  • thanks for your answering but although i never implement your answer if you don't mind can you check my newly updated answers yet with another problem after copying the file is successful yet its not updating the listview of the newer content present? Can you help i've have been stick with this problem for hours... – Vivian May 19 '11 at 15:09