0
private ArrayList<PhotoInfo> imagelist;


imagelist = new ArrayList<>();

imagelist = response.body().getPhotos();

I have to save images in shared preference

and retrieve from as Arraylist

2
  • 2
    what you need is a serialization of POJO classes. use parcellable or serializable or GSON for that. developer.android.com/reference/android/os/Parcelable github.com/google/gson Commented Sep 27, 2019 at 6:08
  • why not save them in a local sqlite database? the solutions provided are very inefficient if you have a lot of data Commented Sep 27, 2019 at 13:39

4 Answers 4

3

Hey I made this easy methods for Save & Get any custom model's ArrayList into SharedPreferences.

Gson dependency required for this:

implementation 'com.google.code.gson:gson:2.8.5'

Save any custom list into SharedPreferences:

public void saveMyPhotos(ArrayList<PhotoInfo> imagelist ) {
    SharedPreferences  prefs = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = prefs.edit();
    try {
        Gson gson = new Gson();
        String json = gson.toJson(imagelist);
        editor.putString("MyPhotos", json);
        editor.commit();     // This line is IMPORTANT !!!
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Get all my saved photos from SharedPreferences:

private ArrayList<PhotoInfo> getAllSavedMyPhotos() {
    SharedPreferences  prefs = PreferenceManager.getDefaultSharedPreferences(this);    
    Gson gson = new Gson();
    String json = prefs.getString("MyPhotos", null);
    Type type = new TypeToken<ArrayList<PhotoInfo>>() {}.getType();
    return gson.fromJson(json, type);
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Rajesh Glad that this helps you.. :)
0

You can convert your arraylist in string using gson library and store and get in SharedPreferences code in bellow

Add this in gradle dependency

api 'com.google.code.gson:gson:2.8.5'

Convert your list into string and store in SharedPreferences

public static boolean writePhotoInfoJSON(List<PhotoInfo> sb, Context context)
{
    try {
        SharedPreferences mSettings = 
context.getSharedPreferences("yourSharedPreNme", Context.MODE_PRIVATE);

        String writeValue = new GsonBuilder()
                .registerTypeAdapter(Uri.class, new UriSerializer())
                .create()
                .toJson(sb, new TypeToken<ArrayList<PhotoInfo>>() 
 {}.getType());
        SharedPreferences.Editor mEditor = mSettings.edit();
        mEditor.putString("shringName", writeValue);
        mEditor.apply();
        return true;
    } catch(Exception e)
    {
        return false;
    }
  }

Get your Custom Array list

 public static ArrayList<PhotoInfo> readPhotoInfoJSON(Context context)
{
    if(context==null){
        return new ArrayList<>();
    }
    try{
        SharedPreferences mSettings = 
context.getSharedPreferences("yourSharedPreNme", Context.MODE_PRIVATE);

        String loadValue = mSettings.getString("shringName", "");
        Type listType = new TypeToken<ArrayList<PhotoInfo>>(){}.getType();
        return new GsonBuilder()
                .registerTypeAdapter(Uri.class, new UriDeserializer())
                .create()
                .fromJson(loadValue, listType);
    }catch (Exception e){
        e.printStackTrace();
    }
    return new ArrayList<>();
}





public static class UriDeserializer implements JsonDeserializer<Uri> {
    @Override
    public Uri deserialize(final JsonElement src, final Type srcType,
                           final JsonDeserializationContext context) throws 
JsonParseException {
        return Uri.parse(src.toString().replace("\"", ""));
    }
}

public static class UriSerializer implements JsonSerializer<Uri> {
    public JsonElement serialize(Uri src, Type typeOfSrc, 
JsonSerializationContext context) {
        return new JsonPrimitive(src.toString());
    }
}

Comments

0

Firstly, you need to implement Serializable interface in your model class

Next, add implementation 'com.google.code.gson:gson:2.8.2' in your module level build.gradle file

Then, you can save/retrieve your Arraylist to/from shared prefrences in this way :

SharedPreferences preferences = context.getSharedPreferences(context.getString(R.string.preference_file_key), Context.MODE_PRIVATE);

public List<?> getListObject(String key, Class<?> T) {
    Gson gson = new Gson();

    ArrayList<String> objStrings = getListString(key);
    ArrayList<?> objects = new ArrayList<>();

    for (String jObjString : objStrings) {
        objects.add(gson.fromJson(jObjString, (Type) T));
    }
    return objects;
}

private ArrayList<String> getListString(String key) {
    return new ArrayList<>(Arrays.asList(TextUtils.split(preferences.getString(key, ""), "‚‗‚")));
}

private void putListString(String key, ArrayList<String> stringList) {
    String[] myStringList = stringList.toArray(new String[stringList.size()]);
    preferences.edit().putString(key, TextUtils.join("‚‗‚", myStringList)).apply();
}

public void putListObject(String key, List<Category> objArray) {
    Gson gson = new Gson();
    ArrayList<String> objStrings = new ArrayList<>();
    for (Object obj : objArray) {
        objStrings.add(gson.toJson(obj));
    }
    putListString(key, objStrings);
}

Comments

0
  1. Save Arraylist

    public static void saveSharedPreferencesLogList(Context context, ArrayList<MenuItemsData> collageList) {
        SharedPreferences mPrefs = context.getSharedPreferences("PhotoCollage", context.MODE_PRIVATE);
        SharedPreferences.Editor prefsEditor = mPrefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(collageList);
        prefsEditor.putString("myJson", json);
        prefsEditor.commit();
    }
    
  2. Get Arraylist

    public static ArrayList<MenuItemsData> loadSharedPreferencesLogList(Context context) {
       ArrayList<MenuItemsData> savedCollage = new ArrayList<MenuItemsData>();
       SharedPreferences mPrefs = context.getSharedPreferences("PhotoCollage", context.MODE_PRIVATE);
       Gson gson = new Gson();
       String json = mPrefs.getString("myJson", "");
       if (json.isEmpty()) {
           savedCollage = new ArrayList<MenuItemsData>();
       } else {
           Type type = new TypeToken<ArrayList<MenuItemsData>>() {
           }.getType();
           savedCollage = gson.fromJson(json, type);
       }
    
       return savedCollage;
    

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.