-1

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;
        }


    }
Santanu Sur
  • 10,997
  • 7
  • 33
  • 52
ibrahem ahmed
  • 25
  • 1
  • 4
  • 1
    Does this answer your question? [store and retrieve a class object in shared preference](https://stackoverflow.com/questions/5418160/store-and-retrieve-a-class-object-in-shared-preference) – Ohad Jan 14 '20 at 20:35

2 Answers2

0

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

Dressy Fiddle
  • 163
  • 10
0

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.