Android - 下载并存储JSON,以便APP可以脱机工作

时间:2015-07-28 07:33:51

标签: android json android-asynctask storage offline

其他开发者。

我是一名刚入学的初级Android开发人员。我需要开发一个应用程序,显示一个ListView,其中包含从Internet下载的一些内容。问题是,JSON有点“大”,因此,用户可以通过WiFi下载JSON,如果网络连接不好,他们可以使用数据的“本地副本”。而不必用慢速互联网再次下载它。

有什么方法可以用AsyncTask或其他任何东西下载JSON编码的信息并将其存储在本地,这样我以后可以打开它并再次加载ListView内容?

谢谢:)

2 个答案:

答案 0 :(得分:1)

首先要做的事情是:Read this知道你有什么样的选择。

现在回答您关于如何在本地保存here代码中的数据的问题:

String FILENAME = "hello_file";
String yourJSON = downloadedJSON.toString() // depends what kind of lib you are using

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(yourJSON.getBytes());
fos.close();

将FILENAME存储在SharedPreferences中,以便以后可以更改,或者只是为了了解如何在SharedPreferences中存储数据:

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); // PREFS_NAME should be a static final String property
SharedPreferences.Editor editor = settings.edit();
editor.putString("myFileName", FILENAME).commit();

然后,当您稍后重新打开应用程序时,您可以这样做:

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String FILENAME = setting.getString("myFileName", "");
if (!FILENAME.isEmpty()) {
   readFile(FILENAME);
}

最后从here:

String的形式回复该文件
FileInputStream fis;
fis = openFileInput("test.txt");
StringBuffer fileContent = new StringBuffer("");

byte[] buffer = new byte[1024];

while ((n = fis.read(buffer)) != -1) { 
  fileContent.append(new String(buffer, 0, n)); 
}

在使用此代码之前,请尝试了解每个代码块。如果您遇到困难,请浏览Android文档并使用Google。 Plenty of tutorials out there。数据存储是基础,不仅仅适用于Android!

答案 1 :(得分:0)

你可以使用这个库:

http://loopj.com/android-async-http/

此库支持GET / POST方法来请求并接收来自您服务的响应。

之后,您可以通过SQLite或Android偏好设置保存数据:

http://www.tutorialspoint.com/android/android_sqlite_database.htm http://www.tutorialspoint.com/android/android_shared_preferences.htm