如何在Android中从Gson存储和检索对象? [英] How to store and retrieve an object from Gson in android?

查看:301
本文介绍了如何在Android中从Gson存储和检索对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的活动中,用户拥有他选择的图像阵列,然后我要将其存储在首选项中.然后用户离开活动,然后返回,我希望这些图像仍加载到 ImageView 中.我正在尝试使用Gson完成此操作,但是遇到了麻烦,看不到我在做什么错. 希望外部见识可以帮助我解决这个我没有看到的明显答案.

In my activity, the user has an array of images he picks, and then I want to store them in preferences. Then the user leaves the activity, and comes back, I want those images still loaded into an ImageView. I'm trying to use Gson to accomplish this, but am having trouble and can't see what I'm doing wrong. Hoping external insight may help me with this obvious answer I'm just not seeing.

谢谢.

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

Here is my code so far.

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.
}

推荐答案

在检索数据的过程中,您将需要一种将字符串反序列化为图像列表的类型...

In the part of retrieving the data you will need a type that deserialize the String into a List of Images...

喜欢:

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);
}

这篇关于如何在Android中从Gson存储和检索对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆