【问题标题】:How to save Firebase DataSnapshot object to shared Preferences?如何将 Firebase DataSnapshot 对象保存到共享首选项?
【发布时间】:2017-01-22 01:45:31
【问题描述】:

我正在尝试将 Firebase DataSnapshot 对象保存到 sharedpreferences。

请参阅this post,其中我设计了一种涉及这样做的方法。

...

到目前为止我所尝试的:

  1. 使用Gson.Json method。结果:似乎不起作用...我不认为 DataSnapshot 类是“POJO”类型的类...至少不能与 gson 一起使用。

  2. 使用这种方法:

    私有静态字符串 toString(Serializable o) 抛出 IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( baos ); oos.writeObject(o); oos.close(); 返回 Base64.getEncoder().encodeToString(baos.toByteArray()); }

结果:不起作用...我不认为 DataSnapshot 类是“可序列化的”。

我想到了另一种方法——只需将 DataSnapshot.toString() 保存到 Sharedpreferences 中...但是如何将其重新取出?你不能这样做:

DataSnapshot snapshot = new DataSnapshot().fromString([string from sharedprefs])

欢迎任何帮助。

【问题讨论】:

  • 您不应该在 sharedpreferences 中保存大量 数据
  • 你怎么知道它有多大,你看到我的数据库了吗?多大才算太大?
  • 这是在共享偏好中存储数据快照的不好方法,这在技术上是不可行的
  • 无论数据大小如何,我的“建议”仍然有效。我建议您寻找替代方案
  • Firebase 支持直接 enablePersistenceStorage 进行离线支持

标签: android serialization firebase sharedpreferences snapshot


【解决方案1】:

我遇到了同样的问题。我想将 Datasnapshot 保存在 SharedPreferences 中,而我的 json 数据有点复杂。所以我写了下面的代码。

//保存到sharedpreference

 public void setAppLanguageDataSnapshot(DataSnapshot mDataSnapshot) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
        String json = mapper.writeValueAsString(mDataSnapshot.getValue());
        StorageUtils.getInstance(context).setString(AppConstants.SharedPrefConstants.APP_CONTENT, json);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
   }

//以JSON对象的形式获取数据。

 String data = StorageUtils.getInstance(context).getString(AppConstants.SharedPrefConstants.APP_CONTENT);
    String value = "";
    if (!TextUtils.isEmpty(data)) {
        try {
            JSONObject jsonObject = new JSONObject(data);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

【讨论】:

    猜你喜欢
    • 2018-02-06
    • 1970-01-01
    • 2011-12-18
    • 2016-01-17
    • 2013-09-20
    • 2021-05-31
    • 2022-01-15
    • 2014-01-16
    • 2017-12-02
    相关资源
    最近更新 更多