【问题标题】:Save 5 json file contents to a cache: Choose SharedPrefs rather than an internal file将 5 个 json 文件内容保存到缓存:选择 SharedPrefs 而不是内部文件
【发布时间】:2014-04-15 05:32:54
【问题描述】:

我的问题是读取内部文件的性能。它真的很慢。我没有测量时间,但恕我直言,它真的很慢。读取这样的文件需要 2-3 秒:

private static String readJsonFile(String type, Context context) {
    int ch;
    StringBuffer sb = new StringBuffer("");
    FileInputStream fis = null;
    try {
        fis = context.openFileInput(context.getResources().getString(R.string.class.getField("filename_" + type).getInt(null)));
        while ((ch = fis.read()) != -1) {
            sb.append((char)ch);
        }
    } catch (NotFoundException | IllegalAccessException | IllegalArgumentException | NoSuchFieldException | IOException e) {
        e.printStackTrace();
    }
    String jsonString = new String(sb);
    return jsonString;
}

数据被写入应用程序的初始屏幕,该应用程序使用 AsyncTask 下载 5 个不同的 json 输入字符串。

我想知道将数据保存在共享首选项中是否会更快,以便访问所有活动中的数据。所以我不需要进行文件访问操作。但是SharedPrefs不也是文件访问操作,读取一个xml文件吗?

或者我应该调用所有需要通过引用函数参数访问全局可用的json数据的函数吗?这行得通吗?

长话短说: 我需要一个模式/模式来说明如何在我的应用程序的生命周期中存储 5 个不同的 JSON 数据字符串,以便每个活动都可以访问它们,而无需执行文件操作或数据库请求?

是否有某种应用程序缓存可以做到这一点?

编辑:我的另一个想法是使用 HttpResponseCache 并启动 asyncActivity 下载数据(在这种情况下是从缓存中)。但这不也是文件读取操作吗?

谢谢

【问题讨论】:

标签: android json performance file caching


【解决方案1】:

我最终使用了一个扩展的应用程序类,其中包含我的全局变量。这很快,而且我不必一直读取文件。此外,我不必在片段构造函数中使用尽可能多的参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-16
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 2019-01-08
    • 2023-03-10
    相关资源
    最近更新 更多