如何在Android中存储和检索Gson中的对象?

时间:2016-06-20 16:08:08

标签: android gson sharedpreferences android-preferences

在我的活动中,用户拥有他选择的一系列图像,然后我想将它们存储在首选项中。然后用户离开活动,然后返回,我希望这些图像仍然加载到 ImageView 。我试图用Gson来实现这一目标,但我遇到了麻烦,无法看清我做错了什么。 希望外部的洞察力可以帮助我解决这个我没有看到的明显答案。

谢谢。

到目前为止,这是我的代码。

private void savePreferencesForImages(String key, ArrayList<Image> imageList)
    {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        Gson gson = new Gson();
        String json = gson.toJson(imageList);
        editor.putString(key,json);
        editor.commit();
    }


//Storing Local data.
private void loadPreferences()
{
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    Gson gson = new Gson();
    String gsonString = sharedPreferences.getString("userImages", "");
    ArrayList<Image> images = gson.fromJson(gsonString, Image.class);//Ask StackOverflow tomorrow.
}

2 个答案:

答案 0 :(得分:1)

在检索数据的部分,您需要一个将String反序列化为图像列表的类型...

像:

private void loadPreferences()
{
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    Gson gson = new Gson();
    Type type = new TypeToken<List<Image>>() {}.getType();
    String gsonString = sharedPreferences.getString("userImages", "");
    List<Image> images = gson.fromJson(gsonString, type);
}

答案 1 :(得分:1)

您可以做的一件事是单独保存图像,然后在检索时将它们加载到ArrayList中。

class Person {
  constructor(data) { ({name: this.name, title: this.title, school: this.school, bio: this.bio, email: email(this.name)} = data); }
  email(username) {
    return username.replace(/\s/, '.').toLowerCase() + '@' + location.hostname.replace(/[^\.\/\@]+\.[^\.\/]+$/, '');
  }
  profile() {
    return `${this.name} ${this.title}`;
  }
}

var apiSrc = 'api.domain.com';
var slug   = 'people';
fetch(`http://${apiSrc}/${slug}.json`)
  .then(function(response) { return response.json() }) // .then(response => response.json())
  .then(function(api) {
    var content = [];
    var group = [];
    for (var i = 0; i < api[slug].length; i++) { var them = api[slug][i]; new Person(them); }
    for (var i = 0; index < group.length; i++) {
      var them = group[i];
      content.push(them.profile());
      console.log(content.join(''));
    }
  });

这可能是最复杂的方式,但这是我能想到的第一件事。您也可以使用getImage(key)方法创建自己的ImageManager类或其他东西并模拟ArrayList的行为。这将消除尝试保存ArrayList时带来的复杂情况。