jeff_bordon
jeff_bordon

Reputation: 412

Universal image loader - clear cache manually

I'm using Universal Image Loader to display images in my app in listviews. I'm using UnlimitedDiscCache since this is the fastest cache mechanism according to the documentation.

However, I would like to clear the disc cache when my app is closed (e.g. in onStop()) but only the oldest cached files that exceed a given limit should be deleted (like TotalSizeLimitedDiscCache does).

I am aware of ImageLoader.clearDiscCache() but in my case this clears the complete cache since I am using UnlimitedDiscCache before...

So I would like to have the fastest cache mechanism when the user is loading and scrolling the listviews and do the slow cache clear when the user is no longer interacting with the app.

Any ideas how I can achieve this?

Upvotes: 8

Views: 3259

Answers (2)

Cyril Noah
Cyril Noah

Reputation: 15

If you want to clear the cache from the memory, you can use the following code:

MemoryCacheUtils.removeFromCache(imageUri, ImageLoader.getInstance().getMemoryCache());

If you also want to clear the cache in the disk, you can use the following code:

DiscCacheUtils.removeFromCache(imageUri, ImageLoader.getInstance().getDiscCache());

This is a much simpler way of clearing the cache. You can find similar answers in this thread:

How to force a cache clearing using Universal Image Loader Android?

I hope this information was helpful. :)

Upvotes: 0

Deepak Swami
Deepak Swami

Reputation: 3858

check this from here https://stackoverflow.com/a/7763725/1023248 may help you..

@Override
protected void onDestroy() {
// closing Entire Application
android.os.Process.killProcess(android.os.Process.myPid());
Editor editor = getSharedPreferences("clear_cache", Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
trimCache(this);
super.onDestroy();
}


public static void trimCache(Context context) {
try {
    File dir = context.getCacheDir();
    if (dir != null && dir.isDirectory()) {
        deleteDir(dir);

    }
} catch (Exception e) {
    // TODO: handle exception
}
}


public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
    String[] children = dir.list();
    for (int i = 0; i < children.length; i++) {
        boolean success = deleteDir(new File(dir, children[i]));
        if (!success) {
            return false;
        }
    }
}

// <uses-permission
// android:name="android.permission.CLEAR_APP_CACHE"></uses-permission>
// The directory is now empty so delete it

return dir.delete();
}

Upvotes: 1

Related Questions