开发者

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

开发者 https://www.devze.com 2023-04-10 10:54 出处:网络
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 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 开发者_如何学Goto 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();


It will be the opposite of your write XML/JSON. Use openFileInput to get the FileInputStream. Read the stream to a string and then parse it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号