Save ArrayList to SharedPreferences

前端 未结 30 3651
野的像风
野的像风 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:24

    I used the same manner of saving and retrieving a String but here with arrayList I've used HashSet as a mediator

    To save arrayList to SharedPreferences we use HashSet:

    1- we create SharedPreferences variable (in place where the change happens to the array)

    2 - we convert the arrayList to HashSet

    3 - then we put the stringSet and apply

    4 - you getStringSet within HashSet and recreate ArrayList to set the HashSet.

    public class MainActivity extends AppCompatActivity {
        ArrayList arrayList = new ArrayList<>();
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            SharedPreferences prefs = this.getSharedPreferences("com.example.nec.myapplication", Context.MODE_PRIVATE);
    
            HashSet set = new HashSet(arrayList);
            prefs.edit().putStringSet("names", set).apply();
    
    
            set = (HashSet) prefs.getStringSet("names", null);
            arrayList = new ArrayList(set);
    
            Log.i("array list", arrayList.toString());
        }
    }
    

提交回复
热议问题