简体   繁体   中英

How to save a model with SharedPreferences?

I've got class to add some variables inside it. I've created an object from it. Then i've added some value to it. The problem now is, i don't know how to add it inside. SharedPreferences i want to edit the code so i can add it without problems. // class : MainActivity

     public class MainActivity extends AppCompatActivity {


         Times times;

         public static Context context;
         @Override
         protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.activity_main);
             this.context = context;

             times = new Times(5,30);

             // setInt(times);
         }

         public final static String PREFS_NAME = "appname_prefs";

         public static void setInt(String key, int value) {
             SharedPreferences sharedPref = context.getSharedPreferences(PREFS_NAME ,0);
             SharedPreferences.Editor editor = sharedPref.edit();
             editor.putInt(key, value);
             editor.apply();
         }

         public static int getInt(String key) {
             SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, context.MODE_PRIVATE);
             return prefs.getInt(key , 0);
         }
     }


    // class Times:


    public class Times{

        int Houre;
        int Minute;

        public Times(int houre, int minute){
            Houre = houre;
            Minute = minute;
        }

        public void setHoure(int houre){
            Houre = houre;
        }

        public void setMinute(int minute){
            Minute = minute;
        }

        public int getHoure(){
            return Houre;
        }

        public int getMinute(){
            return Minute;
        }


    }

Just add editor.commit(); delete editor.apply(); you can read explanation on shared prefs here https://www.tutorialspoint.com/android/android_shared_preferences.htm

Ohad is correct. SharedPreferences only store primitive types like Int and String. In this case you would have to store each value as its own SharedPreference.

If your data is more complex than what SharedPreferences can handle, consider storing it in a Room database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM