Saving data upon closing app and retrieving that data

后端 未结 5 1904
没有蜡笔的小新
没有蜡笔的小新 2021-01-04 01:07

I know, there are plenty of questions in regards to saving/retrieving data on here. I was doing find looking things up on my own and really thought I could manage to find m

5条回答
  •  我在风中等你
    2021-01-04 01:41

    Best way to achieve that is:

    • create a class. Call it MySettings, or whatever suits you
    • in this class, define the array of ints / booleans you are going to share, as static. Create getter & setter method (property) to access that (also as static methods)
    • add a static load() method to MySettings that reads from SharedPreferences. When you launch the app (in your first activity or better in a subclass of Application) call MySettings.load(). This load method sets the array
    • add a static save() method. Public also. Now you can save from anywhere in you app. This save() method reads the array and writes in SharedPreferences

    Code sample:

    public class MySettings {
        private static List  data;
    
        public static void load() {
            data = new ArrayList();
            // use SharedPreferences to retrieve all your data
    
        }
    
        public static void save() {
            // save all contents from data
        }
    
        public static List getData() {
            return data;
        }
    
        public static void setData(List data) {
            MySettings.data = data;
        }
    }
    

提交回复
热议问题