I am currently using XML or JSON webservices in my various applications.
I just would like to know what would be the easiest way to cache theses answers somehere in text files.
I have been thinking about databases, but this seems quite overcomplicated!
So, what I would like to do is
to store these xml/JSON files in phone memory, should I do something like that?
String FILENAME = "MyXmlFile";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
In the onCreate of my application, I would like to parse this file. As all the tutorials are showing how to parse file from web URL, I never found a way to parse an internal text file. Does someone have an advice on that point?
Thanks.
You can apply SharedPreferences, which is also a XML file. Just parse your JSON/XML first, extract all the pair of key/values then write to your pref file. Next time, when loading onCreate(), just re-load the keys/values from pref.
This sample might give you a start:
http://android-er.blogspot.com/2011/01/example-of-using-sharedpreferencesedito.html
Another way is to use an awesome http-request library. It allows you to use ETag to check if the response is not modified (HTTP 304 Not Modified). If not modified, use JSON from file cache, else make a request to get the new resource.
File latest = new File("/data/cache.json");
HttpRequest request = HttpRequest.get("http://google.com");
//Copy response to file
request.body(latest);
//Store eTag of response
String eTag = request.eTag();
//Later on check if changes exist
boolean unchanged = HttpRequest.get("http://google.com")
.ifNoneMatch(eTag)
.notModified();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With