fix cleaning cache in 'sample' app

This commit is contained in:
Alexey Danilov
2015-10-23 18:06:48 +03:00
parent e4ab124d57
commit c5cf254b74
2 changed files with 50 additions and 6 deletions

View File

@@ -3,9 +3,11 @@ package com.danikula.videocache.sample;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
@@ -13,7 +15,7 @@ import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.ViewById;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
@@ -46,11 +48,11 @@ public class MenuActivity extends FragmentActivity {
@Click(R.id.cleanCacheButton)
void onClearCacheButtonClick() {
File externalCacheDir = getExternalCacheDir();
if (externalCacheDir != null) {
for (File cacheEntry : externalCacheDir.listFiles()) {
cacheEntry.delete();
}
try {
Utils.cleanDirectory(getExternalCacheDir());
} catch (IOException e) {
Log.e(null, "Error cleaning cache", e);
Toast.makeText(this, "Error cleaning cache", Toast.LENGTH_LONG).show();
}
}

View File

@@ -0,0 +1,42 @@
package com.danikula.videocache.sample;
import java.io.File;
import java.io.IOException;
/**
* Some utils methods.
*
* @author Alexey Danilov (danikula@gmail.com).
*/
public class Utils {
public static void cleanDirectory(File file) throws IOException {
if (!file.exists()) {
return;
}
File[] contentFiles = file.listFiles();
if (contentFiles != null) {
for (File contentFile : contentFiles) {
delete(contentFile);
}
}
}
private static void delete(File file) throws IOException {
if (file.isFile() && file.exists()) {
deleteOrThrow(file);
} else {
cleanDirectory(file);
deleteOrThrow(file);
}
}
private static void deleteOrThrow(File file) throws IOException {
if (file.exists()) {
boolean isDeleted = file.delete();
if (!isDeleted) {
throw new IOException(String.format("File %s can't be deleted", file.getAbsolutePath()));
}
}
}
}