【问题标题】:Android - Download and store JSON so APP can work offlineAndroid - 下载并存储 JSON,以便 APP 可以离线工作
【发布时间】:2015-10-18 15:23:15
【问题描述】:

开发人员。

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

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

谢谢你:)

【问题讨论】:

  • 多种方式.. 将数据存储在数据库中,使用 FileInputOutputStream、sharedpreferences 等将数据写入文件

标签: android json android-asynctask storage offline


【解决方案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!

【讨论】:

  • 非常感谢ezCoding。我今天下班后会检查一切:)
  • Arf,我仍然无法测试这个,但我会尽快接受答案,看看它是否有效(我希望它会)。抱歉回复迟了!
【解决方案2】:

你可以使用这个库:

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

【讨论】:

    猜你喜欢
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 2016-11-23
    • 1970-01-01
    • 2016-10-25
    相关资源
    最近更新 更多