I am using Jake Wharton’s LRU disk cache to store and retrive bitmaps that are displayed in a ListView. This works fine so long as I store and access bitmaps from within the same activity. However, if I try to access the cach from other activities within the app (i.e. so I don’t have to downlaod the same image twice) I get a NullPointerException. Am I missing something here? This isn’t a memory cache where the files could/would be removed. Shouldn’t the disk cache be accessable from all the activites within the app, so long as I point them to the right directory within the internal storage?
01-14 22:53:44.465: E/AndroidRuntime(10720): java.lang.NullPointerException
01-14 22:53:44.465: E/AndroidRuntime(10720): at java.util.regex.Matcher.reset(Matcher.java:181)
01-14 22:53:44.465: E/AndroidRuntime(10720): at java.util.regex.Matcher.<init>(Matcher.java:94)
01-14 22:53:44.465: E/AndroidRuntime(10720): at java.util.regex.Pattern.matcher(Pattern.java:290)
01-14 22:53:44.465: E/AndroidRuntime(10720): at com.example.echofriendly.DiskLruCache.validateKey(DiskLruCache.java:629)
01-14 22:53:44.465: E/AndroidRuntime(10720): at com.example.echofriendly.DiskLruCache.get(DiskLruCache.java:375)
01-14 22:53:44.465: E/AndroidRuntime(10720): at com.example.echofriendly.DiskLruImageCache.containsKey(DiskLruImageCache.java:145)
01-14 22:53:44.465: E/AndroidRuntime(10720): at com.example.echofriendly.ChatroomFragment.getMessages(ChatroomFragment.java:309)
01-14 22:53:44.465: E/AndroidRuntime(10720): at com.example.echofriendly.ChatroomFragment.access$3(ChatroomFragment.java:284)
01-14 22:53:44.465: E/AndroidRuntime(10720): at com.example.echofriendly.ChatroomFragment$2.run(ChatroomFragment.java:94)
01-14 22:53:44.465: E/AndroidRuntime(10720): at java.lang.Thread.run(Thread.java:1019)
Sounds like you are instantiating the cache in every Activity where you need it. I don’t think that is a good idea. Since Jake’s LruCache uses a journal different instances that work on the same directory could in my opinion easily distract each other.
My suggestion is that you introduce some kind of singleton either as a layer between the activities and the cache or to just store the reference to exactly one cache instance for the whole application.
Furthermore I would suggest that you use some kind of two-level cache, e.g. a memcache combined with a diskcache (this is what I do in my app). So you can first check the memcache and get the image really fast if it was cached there. (can be synchronous) If it is not there you ask the diskcache. (should be asynchronous) And as last call you would download it. (also asynchronous)