Tuesday, May 21, 2019

Android SharedPreferences , how to save a simple int variable




I am trying for the last hour to save an integer in my Android application. I read that this can be done using the SharedPreferences. However i dont understand why it seems so confusing to do so.



How can i simply save an int variable ? And then when i run the application again , how can i interact with this variable again?


Answer



SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("your_int_key", yourIntValue);

editor.commit();


the you can get it as:



 SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
int myIntValue = sp.getInt("your_int_key", -1);


The SharedPreference interface gives you access to the an xml file, and a easy way to modify it through its editor. The file is stored in /data/data/com.your.package/shared_prefs/ and you can access it onlu through this SharedPreference API



No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...