SharedPreferences int not updated after apply - android

I am running:
int value = mPreferences.getInt(key, 0);
mPreferences.edit().putInt(key, value+1).apply();
int newValue = return mPreferences.getInt(key, 0);
However I get the same result for value and newValue. The updated result only appears when I call getInt() later in the code. I thought updates to the SharedPreferences object using apply() would instantly be visible in the SharedPreferences object. Is this not the case?

If you want synchronous update you have to use
commit()
http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#commit()

First of all commit() & apply() are the almost the same, major difference been that apply() is faster
I tried doing it the same way & it worked for me
Check this :
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
int a = sharedPreferences.getInt("a",0);
Toast.makeText(getActivity(), "a = " + a , Toast.LENGTH_SHORT).show();
sharedPreferences.edit().putInt("a", a+1).apply();
After checking the xml in data of the app, I got a as 1

Related

Android: Unbale to save boolean in SharedPreferences

Hey guys I am unable to save a boolean value using SharedPreferences. The value is ALWAYS true for some reasons. Here is how I save the value:
public static void setSharedPreference(Context ctx, String keyValue, boolean value){
SharedPreferences sp = ctx.getSharedPreferences(Constants._preferencesName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean(keyValue,value);
editor.commit();
}
And this is how I get it back:
public static boolean getBooleanPreference(Context ctx, String keyValue){
boolean prefValue;
SharedPreferences sp = ctx.getSharedPreferences(Constants._preferencesName, ctx.MODE_PRIVATE);
prefValue = sp.getBoolean(keyValue, false);
return prefValue;
}
What is wrong?!
Your code is syntactically correct, but I suspect you are passing different Context while saving than you are passing while reading from prefs. This will result in accessing different shared preferences storage. This is especially easy to step on if you are doing your writes and reads in different activities and decide to pass this as context. Unless there's a reason for doing so then you most likely want to reach your preferences from anywhere in your app then use always application context instead (getApplicationContext()).
Everything is correct in your code.
The ONLY possibility of a mistake is when you are calling these methods. Please use getApplicationContext() while putting and retrieving data.
And please do a "Clear data" for the app and start with a clean SharedPreference.

How to put a database with data in SD card only once-when the application is installed

I have a database which contains data. How is it possible to put the database in SD card only once? i mean -while it is being installed?
And also want some pictures to be pushed too.
Help me out please.
You can try SharedPreferences
private static final String FIRST_RUN = "first_run";
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences();
//Assume true if the key does not yet exist
if (prefs.getBoolean(FIRST_RUN, true)) {
//Do your database operations
..............................................
} else {
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(FIRST_RUN, false);
edit.commit();
}
just set one shared preference at first activity like splash of your app with Boolean value of false and do your work with database whatever u want in that condition after that set it with value true then it will not call that function until unless you re-install it or just not clear your data forcibly.

Saving and Getting Level Number [duplicate]

This question already has answers here:
How can I save an activity state using the save instance state?
(35 answers)
How to save app settings?
(6 answers)
Closed 8 years ago.
I'm developing a level-based app, and I want to be able to save the user's level number (1, 2, 3 etc..) and then when the app starts get the level number and do something with it.
How can I do it?
Use Shared Preferences like so:
Create these methods for use, or just use the content inside of the methods whenever you want:
public int getLevel()
{
SharedPreferences sp = getSharedPreferences("prefName", 0);
int level = sp.getInt("levelReference", 1);
return level;
}
public void setLevel(String level)
{
SharedPreferences.Editor editor = getSharedPreferences("prefName", 0).edit();
editor.putInt("levelReference", level);
editor.commit();
}
The 1 in sp.getInt("levelReference", 1); means that the method will return 1 if the preference is not found, so the default level is 1.
You can call them like this:
int level = getLevel(); // level is now the level that the user is on
setLevel(4); // user is now on level 4
Use SharedPreferences for storing level number:
http://developer.android.com/reference/android/content/SharedPreferences.html
http://android-er.blogspot.ru/2011/01/example-of-using-sharedpreferencesedito.html
If you read up in the documentation here you can see that to save data like a level number, you can use SharedPreferences. First, you'll need a SharedPreferences object, which you can obtain using
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
Then to save a piece of data, use:
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("level", level);
editor.commit();
And finally, to get that level back later, use:
sharedPref.getInt("level", 0);
Good luck!

Can't Get Shared Preference Value Even Though Values Exist

Any time I try to getInt() from a SharedPreference my app crashes, yet I can iterate through the preferences as a map. For instance, see the starred lines below:
private void loadPref(){
myPrefs = PreferenceManager.getDefaultSharedPreferences(this);
int sf = DEFAULT_VALUE;
Map<String,?> keys = myPrefs.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
if (entry.getKey().contentEquals("score_format"))
// this works: //*****
sf = Integer.parseInt(entry.getValue().toString()); //*****
}
// but this does not: //*****
// sf = myPrefs.getInt("score_format", DEFAULT_VALUE); //*****
setScoreFormat(sf);
}
Clearly, my prefs are being saved (as evidenced by this sample and working preference screens across multiple activities). I am calling super.onCreate() before trying to access getDefaultSharedPreferences.
What should I be considering to understand why this code is not working? Why would the map work but not the "getInt" method? I did notice that the app would also crash if I tried to cast the key value explicitly... I had to cast it toString first.
What am I missing?
if you don't want to parse, make sure the score you're putting into the intent with putExtra is an int type, not a string.
Looks like object assosiated with score_format key is a String but you are trying to obtain it as int which is a mistake.

Why cannot save INT to SharedPreferences?

I have a strange problem. I have never had it before. When I try to save int value to my SharedPreference and then restore in other Activity. Value is always 0 even if I save there other value (for example: 1);
private String Number;
private String Profile;
and then saving values (in this case "1") to SharedPreferences in first Activity:
SharedPreferences a = FirstActivity.this.getSharedPreferences("a", MODE_PRIVATE);
SharedPreferences.Editor prefsEditorProfiles = a.edit();
prefsEditorProfiles.putInt(Profile, 1);
prefsEditorProfiles.putInt(Number, 1);
prefsEditorProfiles.commit();
then restore SharedPreferences in other Activity:
SharedPreferences a = SecondActivity.this.getSharedPreferences("a", MODE_PRIVATE);
int ab = a.getInt(Number, 0);
And application shows me 0 instead of 1. My other SharedPreferences works great. I don't know where is the problem.
I'd check what's the value of the Number and Profile variables you declared... you are using their values as keys, so if they have conflicting names, you might be overwriting one setting with the other even though the code looks right.
I'd recommend replacing this:
private String Number;
private String Profile;
With this:
private final String NUMBER = "Number";
private final String PROFILE = "Profile";
And then using those constants when setting/getting your preference value.
Do you ever set a value for
"Number" and "Profile"?
If not then that is your problem -those strings are null.
Please try to use
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
rather than using
SharedPreferences prefs = getActivity().getSharedPreferences ("PREFS_KEY", 0);
when Storing int in shared preference
I've been trying for a while to use putInt like you but it always give an error.
prefsEditorProfiles.putInt(Number, 1);
by just changing a.putInt to a.putString and retrieving it with a.getString I was able to have the correct value.
so, I guess there should be something wrong with putInt and getInt.
Anyway, try that also to have the correct value you need to continue for application.

Categories

Resources