Search code examples
androidgsonsharedpreferencesandroid-preferences

How to store and retrieve an object from Gson in android?


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.

Thank you.

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

Solution

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

    like:

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