0

I am using shared preferences and would like the default value to be 1 when there are no preferences found.

My code

int currentRadio;
...
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
currentRadio = prefs.getInt("radioSelected", 1);

I am unsure why I am not getting 1 for the default value.

To test I would uninstall the app from my phone then launch the app to my phone from android studio. Every time I get 2 as the default value. However, if I just clear the data from the app, I get 1 as the default value.

Any help is appreciated, thank you.

Jon
  • 278
  • 8
  • 23
  • which android version? – sanky jain Mar 03 '16 at 06:06
  • there will be problem in your implementation. because it should return 1 if nothing found. else it will be null. but you are saying `it returns 2`. so I am guessing you either previously storing some value in it or you assigning some value to `currentRadio` – Shabbir Dhangot Mar 03 '16 at 06:08
  • @jon did you save 2 to your shared preference before uninstalling your app? If yes then try my solution. – sanky jain Mar 03 '16 at 06:14
  • @sankyjain no it doesn't matter what I save in shared preferences before hand. It returns 2 regardless when I first start after a new install. – Jon Mar 03 '16 at 22:06

4 Answers4

3

Just Go through this:

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

Then 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

Actually, you also need to provide a default value to getInt which is returned when an int with the key your_int_key could not be found. Something like this:

   int myIntValue = sp.getInt("your_int_key", -1);

where -1 is the default value

Also, If you use API 9 or above you should use apply() instead of commit()

0

declare prefs like:

prefs = PreferenceManager.getDefaultSharedPreferences(context);
Akbar
  • 430
  • 4
  • 18
0

It would be happening due to you wrong implementation of shared preference. Do one thing search for the key "radioSelected" in you app. if it found at any other place to save the value in shared preference, then make it comment.

Or just share your complete shared preference file.

Ashish Rajvanshi
  • 466
  • 4
  • 15
-2

If using android-21 the problem is not with preferences. Its with backup manager

Add in manifest file

android:allowBackup="false" 
sanky jain
  • 873
  • 1
  • 6
  • 14