Reputation: 39
I'm working on my first android app, which is a cache cleaner for another very popular app. I've finally got functionality for checking the app cache, then deleting it if one exists. However, the Async task I've setup for deleting the files doesn't seem to update the progress bar accurately. As I am a programming n00b, my code is mostly copypasta from other sources.
Here's the block I suspect has the progress bar calculation issue:
@Override
protected Void doInBackground(Void... params) {
// Delete Cache !!
File dir = new File(Environment.getExternalStorageDirectory()
+ "/Android/Data/com.popularapp/Cache");
// Progress Bar
for (int i = 1; i < 100; i++) {
if (isCancelled()) {
break;
} else {
System.out.println(i);
publishProgress(i);
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i2 = 0; i2 < children.length; i2++) {
new File(dir, children[i2]).delete();
}
}
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
tvLoading.setText("Loading... " + values[0] + " %");
tvPer.setText(values[0] + " %");
}
Upvotes: 0
Views: 187
Reputation: 2290
It seems as though your nested for loops are a unnecessary an you only need one to go through the directory. You should tie your progress to the iteration of the for loop that actually deletes the files.
You can remove your outer for loop and publish progress with your 'i2' counter variable.
Inside your second (now first) for loop call your publishProgress(i2 / children.length * 100). That should be a more accurate number, assuming all files take about the same amount of time to delete (probably a moderately safe assumption for your purposes).
@Override
protected Void doInBackground(Void... params) {
// Delete Cache !!
File dir = new File(Environment.getExternalStorageDirectory()
+ "/Android/Data/com.popularapp/Cache");
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i2 = 0; i2 < children.length; i2++) {
if (isCancelled()) break;
int progress = 100 * i2 / children.length;
Log.w("Deleting files...", "Current iteration: " + i2 + " Progress: " + progress);
publishProgress(progress);
new File(dir, children[i2]).delete();
}
}
return null;
}
Upvotes: 1