Save ArrayList to SharedPreferences

前端 未结 30 3555
野的像风
野的像风 2020-11-21 04:43

I have an ArrayList with custom objects. Each custom object contains a variety of strings and numbers. I need the array to stick around even if the user leaves

30条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 05:04

    Hey friends I got the solution of above problem without using Gson library. Here I post source code.

    1.Variable declaration i.e

      SharedPreferences shared;
      ArrayList arrPackage;
    

    2.Variable initialization i.e

     shared = getSharedPreferences("App_settings", MODE_PRIVATE);
     // add values for your ArrayList any where...
     arrPackage = new ArrayList<>();
    

    3.Store value to sharedPreference using packagesharedPreferences():

     private void packagesharedPreferences() {
       SharedPreferences.Editor editor = shared.edit();
       Set set = new HashSet();
       set.addAll(arrPackage);
       editor.putStringSet("DATE_LIST", set);
       editor.apply();
       Log.d("storesharedPreferences",""+set);
     }
    

    4.Retrive value of sharedPreference using retriveSharedValue():

     private void retriveSharedValue() {
       Set set = shared.getStringSet("DATE_LIST", null);
       arrPackage.addAll(set);
       Log.d("retrivesharedPreferences",""+set);
     }
    

    I hope it will helpful for you...

提交回复
热议问题