Save ArrayList to SharedPreferences

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

    For String, int, boolean, the best choice would be sharedPreferences.

    If you want to store ArrayList or any complex data. The best choice would be Paper library.

    Add dependency

    implementation 'io.paperdb:paperdb:2.6'
    

    Initialize Paper

    Should be initialized once in Application.onCreate():

    Paper.init(context);
    

    Save

    List contacts = ...
    Paper.book().write("contacts", contacts);
    

    Loading Data

    Use default values if object doesn't exist in the storage.

    List contacts = Paper.book().read("contacts", new ArrayList<>());
    

    Here you go.

    https://github.com/pilgr/Paper

提交回复
热议问题