1

I I have ab ArrayList which is containing ArrayLists, they are again containing lists. One of Strings and one of Views. How could i save This root list to Shared Preferences or in any other was? Here is an overview:

           MotherList
                | 
                .
          DaughterLists
            /       \
           /         \
    ListOfViews  ListOfStrings
                .
                .
Andrej Istomin
  • 2,527
  • 2
  • 15
  • 22
RedDragon
  • 11
  • 1

3 Answers3

0

Here are all of methods about put data in SharedPreferences: putBoolean(String key,boolean v) putInt(String k,int v) putFloat(String k,float v) putLong(String k,long v) putString(String k,String v) putStringSet(String k,Set v)

But there is a open-source frame called ASimpleCache can solve it:

save: ACache acache = ACache.get(Context); acache.put("key",your-root-list); get: acache.getAsObject("key");

xinxin yao
  • 31
  • 3
0

Store Arraylist Using Shared Preferences

SharedPreferences prefs=this.getSharedPreferences("yourPrefsKey",Context.MODE_PRIVATE);
Editor edit=prefs.edit();

Set<String> set = new HashSet<String>();
set.addAll(your Arraylist Name);
edit.putStringSet("yourKey", set);
edit.commit();

Retrieve Arraylist from Shared Preferences

Set<String> set = prefs.getStringSet("yourKey", null);
List<String> sample=new ArrayList<String>(set);
Tushar Narang
  • 1,997
  • 3
  • 21
  • 49
0

Hello I suggest you to use GSON , for serializing and deserializing your list. By this way you can save it on your SharedPreferences easily.

  1. First convert your ArrayList<List> object to JSON with help of GSON Converter

    String myArrayListAsJSON = new Gson().toJson(myArrayList); // you will pass your arraylist variable to toJson() method
    
  2. Save your JSON Object as String on your SharedPreference

    SharedPreferences prefs=this.getSharedPreferences("PREF_KEY_FOR_YOUR_APP",Context.MODE_PRIVATE);
    Editor edit=prefs.edit();
    
    edit.putString("myListKey", myArrayListAsJSON); // we will put our list hat serialized with GSON here
    edit.commit();
    
  3. Re-use your list at any place/time of your application. You will just need to deserialize your JSON that you saved on your Shared Preferences

    SharedPreferences prefs=this.getSharedPreferences("PREF_KEY_FOR_YOUR_APP",Context.MODE_PRIVATE);
    String myListAsString = prefs.getString("myListKey","default_value");
    ArrayList<List> yourObject = new Gson().fromJson(myListAsString, YOUR_MODEL.class);
    

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

You can use GSON in your app by adding this line to your dependencies.

compile 'com.google.code.gson:gson:2.6.2'

You can find more detail and example on GSON Github Page

Emin Ayar
  • 1,104
  • 9
  • 13