简体   繁体   English

每次加载时将JSON文件缓存到内部存储中

[英]Caching JSON file to internal storage on each load

I have an Android app that loads a remote JSON feed every 5 seconds. 我有一个Android应用程序,每5秒加载一次远程JSON feed。 The payload of the JSON file is about 240kb. JSON文件的有效负载约为240kb。 I would also like to cache this data so that users can view the last loaded feed when they are offline. 我还想缓存此数据,以便用户在脱机时可以查看上一次加载的供稿。

Is it advisable to write the raw data to the internal storage every time the feed is fetched? 每次获取提要时,是否建议将原始数据写入内部存储?

I wouldn't. 我不会 I'd memory cache it, and write the last version to the file system in onPause(). 我会对其进行内存缓存,并在onPause()中将最新版本写入文件系统。 That way you don't constantly write to disk. 这样,您就不会不断地写入磁盘。

I agree with Gabe. 我同意加贝。 Save the data in the onPause() Method. 将数据保存在onPause()方法中。 You can never be certain when the system or user will terminate your app so apply the onPause() Method to every activity in your app, then call a class or static method that will perform the save to the apps cache directory. 您永远无法确定系统或用户何时终止您的应用程序,因此请对应用程序中的每个活动应用onPause()方法,然后调用将执行保存到应用程序缓存目录的类或静态方法。

Best of Luck. 祝你好运。

Why don't you use SharedPreferences? 为什么不使用SharedPreferences?

SharedPreferences sharedPref = getSharedPreferences("Test", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("jsondata", jobj.toString());

... ...

String strJson = sharedPref.getString("jsondata");
if(strJson != null) JSONObject jsonData = new JSONObject(strJson);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM