Android - 下载并存储 JSON 以便 APP 可以离线工作

Android - Download and store JSON so APP can work offline

开发人员。

我是一名刚毕业的初级Android开发人员。我需要开发一个应用程序来显示一个 ListView,其中包含从 Internet 下载的一些内容。问题是,JSON有点"big",所以,用户最好用WiFi下载JSON,万一网络不好,他们可以使用 "local copy" 的数据,而不必在网速较慢的情况下再次下载。

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

谢谢:)

第一要务: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!

你可以使用这个库:

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