Reputation: 6081
in my app I download an XML file. Then that XML file gets assigned to variables. The problem I'm now encountering is that, I want to cache that XML file.
I thought about saving every XML File into different variables, but the problem there would be, that the XML files I download aren't the same. It can be a combination of 4x2x3
possibilites of XML data that can be retrieved. So I thought I would go and only download the file once and then cache it for about 60 seconds. How would I do that?
Currently, I'm downloading a XML file like that:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try{
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
try{
docComplete = db.parse(new InputSource(new URL( BLOGS_ONLY ).openStream()));
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
try {
hashMap = getAccordingData( docComplete );
} catch ( NullPointerException npe ){
mainAsyncTask.cancel(true);
mainAsyncTask.execute( );
}
and the getAccordingData
method just gets the ElementsByTagName
into a NodeList and then with a for-loop adds it to a HashMap that gets returned.
So this is what is happening at the moment. What would your way be to cache it?
Upvotes: 1
Views: 867
Reputation: 15929
If you are looking for a Memory Cache use a LruCache instead of HashMap.
If you only want to cache it for 60 seconds, that you may should consider do write a CacheEntry Class that holds the data and a Timestamp when you have loaded the resource.
But keep in mind that you could run out of memory because the XML Document will be hold in Memory. You may consider to use a disk cache like DiskLruCache (depending on the length of your document). Disk Lru Cache
UPDATE: I think you should use a library like Volley that will do xml parsing and caching for you. I also would recommend you to set the caching period for each xml file in the http headers (which volley will respect). Volley Example
Upvotes: 1