views:

422

answers:

3

Hello,

keeping my question short, I have creating application with 3 activities, where A - list of categories, B - list of items, C - single item. Data displayed in B and C is parsed from online XML. But, if I go trough A -> B1 -> C, then back to A and then back to B1 I would like to have it's data cached somewhere so I wouldn't have to request XML again.

I'm new to Android and Java programming, I've googled a lot and still can't find (or simply do not have an idea where to look) a way to do what I want.

Would storing all received data in main activity A (HashMaps? ContentProviders?) and then passing to B and C (if they get same request that was before) be a good idea?

A: 

You can make use of data storage as explained in Android Reference here http://developer.android.com/guide/topics/data/data-storage.html

the100rabh
It's an option, but I'll have to worry about flushing data at the end of application lifetime?
sniurkst
isnt it a good idea to keep data cached even after the end of app lifetime ?
the100rabh
+2  A: 

A simple and fast way to cache information or to keep track of the application state, is to extend the Application as described in this blog post.

This blog post forgets to add that you have to set your CustomApplication class in the manifest, like:

<application [...] android:name="CustomApplication">

In my projects I stick to the singleton style via getInstance.

More resources: this answer, Global Variables in Android Apps and this blog post.

digitarald
A: 

If you want to build some sort of cache on memory, consider using a Map with SoftReferences. SoftReferences are sort of references that tend to keep your data around for a while, but does not prevent it from being garbage collected.

Memory on a cell phone is scarce, so keeping everything in memory may not be practical. In that case you may want to save your caches on the device's secondary storage.

Check out MapMaker from Google's Collections, which allows you to conveniently build a 2-level cache. Consider doing this:

/** Function that attempts to load data from a slower medium */
Function<String, String> loadFunction = new Function<String, String>() {
    @Override
    public String apply(String key) {
        // maybe check out from a slower cache, say hard disk
        // if not available, retrieve from the internet
        return result;
    }
};

/** Thread-safe memory cache. If multiple threads are querying
*   data for one SAME key, only one of them will do further work.
*   The other threads will wait. */
Map<String, String> memCache = new MapMaker()
                                .concurrentLevel(4)
                                .softValues()
                                .makeComputingMap(loadFunction);

About cache on device's secondary storage, check out Context.getCacheDir(). If you're sloppy like me, just leave everything there and hope that the system will clean things for you when it needs more space :P

Po