Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to cache an XML/JSON response into my application. Full text file?

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

  1. 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();  
    
  2. 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.

like image 311
Waza_Be Avatar asked Nov 05 '22 13:11

Waza_Be


2 Answers

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

like image 138
Pete Houston Avatar answered Nov 09 '22 05:11

Pete Houston


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();
like image 22
Nam Ngo Avatar answered Nov 09 '22 05:11

Nam Ngo