Sharedpreferences: can't get the saved value updated in separate methods - android

I am writing a game app where I need to save the best score and get it back next time a user plays it. So saving happens when the player dies and retrieving (Read) happens when the game starts again: both are in separate methods.
Save:
SharedPreferences myPrefs = getContext().getSharedPreferences(HIGH, Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putInt(HIGHSCORE, best);
prefsEditor.commit();
Read:
SharedPreferences myPrefs = getContext().getSharedPreferences(HIGH, Context.MODE_PRIVATE);
int highestScore = myPrefs.getInt(HIGHSCORE, 1);
best=highestScore;
As you can see the default value when the highestscore is retrieved is 1. But I always end up getting 1! So may be the saving is not happening correctly. Please help. Thanks.

Related

sharedpreferences value not updated

I have a Sharedpreferences to check if the user has activated the pro section with InAppPurchase and I check it every time Mainactivity is opens, like this:
SharedPreferences s = c.getSharedPreferences("app" , MODE_PRIVATE);
String value = s.getString(key , " ");
Log.i("myapp" , value);
and if some one tries to change the value manually my app warns him .so I tried to test my app's security and changed the value manually with text editor from data/data/com.myapp.package/shared_prefs/ let's say the value was 39m49ur3.I changed it a to 87mjr83.Then I started the app and the value from the logs stil was 39m49ur3 . I closed the app and started it again but no change was seen except when I clear the RAM of my device then start the app , finally then the value I got from the logs is what really is in the shared_prefs folder.
What can I do about this?
Save like this,
SharedPreferences pref = c.getSharedPreferences("app", MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("myapp", "string value");
editor.commit();
Get Like this,
pref.getString("myapp", null);
//to save String in shared preferences
public void put(String key, String value) {
mSharedPreferences.edit().putString(key, value).apply();
}
//to get value from shared preferences
public String get(String key, String defaultValue) {
return mSharedPreferences.getString(key, defaultValue);
}
Try to use
editor.apply();
Instead of
editor.commit();
Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures.

How to save value of a string even after the activity/app is destroyed?

I have 2 int in my navigation drawer, the value of whom changes upon clicking different button on different locations in the app.
I got the code to successfully increment and update them, but the problem is that they got reset when I open the app after closing or exiting it.
How can I make them stay there after getting updated?
If you want any code from my app, then please tell me.
Sorry for bad formatting of the question, but I have no idea how to do this and hence I haven't posted any code.
You must save the info in a persistent storage.
You can use SharedPreferences.
SharedPreferences prefs= getSharedPreferences("aName", MODE_PRIVATE);
//save the value
prefs.edit()
.putInt("nameOfTheValue", theValue).apply();
// get the data
prefs.getInt("nameOfTheValue", aDefaultValue);
You should save them as User SharedPreferences in onDestroy method.
public void onDestroy() {
super.onDestroy();
SharedPreferences settings;
settings = getSharedPreferences("TWO_INT_SAVING", Context.MODE_PRIVATE);
//set the sharedpref
Editor editor = settings.edit();
editor.putInt("FIRST_INT", firstIntValue);
editor.putInt("SECOND_INT", secondIntValue);
editor.commit();
}
And then you can get them back wen needed:
SharedPreferences settings;
settings = getSharedPreferences("TWO_INT_SAVING", Context.MODE_PRIVATE);
//get the sharepref
int firstInt = settings.getInt("FIRST_INT", 0);
int secondInt = settings.getInt("SECOND_INT", 0);

Not getting saved SharedPreference value from IntentService

I'm creating a shared preference in my MainActivity and then I want to get a value saved in the shared preference in my IntentService; however; I keep getting the default value rather than the value that I had saved.
This is my code to create the SharedPreference in my MainActivity:
SharedPreferences prefs = this.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
prefs.edit().putString("inter", inter).apply();
And in my IntentService class:
protected void onHandleIntent(Intent intent) {
SharedPreferences preferences = getApplicationContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
final String inter = preferences.getString("inter", "default_no");
}
The problem here is a subtle one:
SharedPreferences.Editor#commit stores the modifications to storage in a blocking fashion, so you are guaranteed that any other instance that queries the value on the same thread will actually get the new one.
SharedPreferences.Editor#apply does so asynchronously so if you fetch the value on another instance of SharedPreferences too fast, it might not get the updated value.
Commit may actually work better on your situation as you are not doing any big change to the preferences. If you need to use apply, you might want to induce a slight delay using Handler#post.
Cheers.
Try using and editor to save your value in SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences(PREFS_NAME, context.MODE_PRIVATE);
SharedPreferences.Editoreditor = pref.edit();
editor.putString("inter", inter);
editor.commit();//This will make your value store in SharedPreferences

How to make a persistent counter variable in an Android app?

I'm just starting out.
I'm trying to increment a simple counter, every time I run the project on the emulator.
I thought adding an integer type item in strings.xml would help, but that's final, and can't be modified.
Basically I'd just display in my app's first basic screen:
Started: N where N would be the Nth time I've launched the project from Eclipse.
How can I make such a counter that's persistent across application launches and exits?
Got it:
SharedPreferences pref = getPreferences(MODE_PRIVATE);
int tempN=pref.getInt("N", 0);
tempN++;
SharedPreferences.Editor editor = pref.edit();
editor.putInt("N",tempN);
editor.commit();
msgBox.setText("Started:"+tempN);
One thing I still don't understand, that when I call pref.getInt("N",0), is the key-value pair <N,0> automatically created?
You can use shared preference for that . You can store integer number in shared preference and get value of it when ever you want.
Try this.
SharedPreferences prefs = getSharedPreferences("Share", Context.MODE_PRIVATE );
Editor editor = prefs.edit();
editor.putInt("Value", 1 );
editor.commit();
for get value
prefs.getInt("Value",0);
In your main activity onCreate():
SharedPreferences pref = this.getSharedPreferences();
int count = pref.getInt("your key", 0) //0 is default value.
count++;
SharedPreferences.Editor edit = pref.edit();
edit.putInt("your key", count);
edit.commit();
// display current count

Data cache in Shared Preference

I have 2 processes in my application. From one process i save data in to SharedPreferences.
From second process - retrieve. When i retrieve data, i receive SharedPreferences with old data(i check xml file and see, that currently data in file and data that was received are different). It looks like this data was cached. I changed saving methods (commit/apply) but no result.
PS: just for example http://pastebin.com/Zx2ffvSg
//saving
{ ...
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString(MY_NAME, "Sai");
prefsEditor.putString(MY_WALLPAPER, "f664.PNG");
prefsEditor.commit();
... }
//retrieving
// when i call getData() I put "this" as argument.
public void getData(Context context){
SharedPreferences myPrefs = context.getSharedPreferences("myPrefs", MODE_PRIVATE);
...}
The solution is add to neccesary flags Context.MODE_MULTI_PROCESS flag when open shared preference (Available in API Level 11 and up)

Categories

Resources