SharedPreferences resetting after process kill - android

Right i know there's a lot of these types of questions on here but i'm yet to find one that works.
For the past 30 minutes or so i've playing with SharedPreferences and so far the values save with no problems at all but when you kill the process by either long pressing the back button or using a task manager and you go to restart the app, it'll go back to default values.
Now the default value is 50, as i'm doing my Equalizer and have a flat/reset button
So yeah, basically how do i save the values and keep them saved?!
Here's my various attempts:
Attempt 1:
private int isFirstTime()
{
SharedPreferences sp = getSharedPreferences("sliders", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
for (int i = 0; i < num_sliders && i < MAX_SLIDERS; i++) {
editor.putInt("sliders", sliders[i].getProgress());
editor.putInt("bass_boost", bass_boost.getProgress());
editor.commit();
}
return num_sliders;
}
Attempt 2:
public int saveProgress(){
SharedPreferences sp = getSharedPreferences("sliders2", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("sliders", sliders[0].getProgress());
editor.putInt("sliders2", sliders[1].getProgress());
editor.putInt("sliders3", sliders[2].getProgress());
editor.putInt("sliders4", sliders[3].getProgress());
editor.putInt("sliders5", sliders[4].getProgress());
editor.putInt("sliders6", sliders[5].getProgress());
editor.putInt("sliders7", sliders[6].getProgress());
editor.putInt("sliders8", sliders[7].getProgress());
editor.putInt("sliders9", sliders[8].getProgress());
editor.putInt("sliders10", sliders[9].getProgress());
editor.putInt("bass_boost", bass_boost.getProgress());
editor.commit();
return min_level - max_level;
}
Attempt 3:
public int getProgress(){
SharedPreferences sp = getSharedPreferences("sliders", MODE_PRIVATE);
for (int i = 0; i < num_sliders && i < MAX_SLIDERS; i++) {
num_sliders = sp.getInt("sliders", 0);
}
num_sliders = sp.getInt("bass_boost", 0);
return num_sliders;
}
Attempt 4:
public int getProgress2(){
SharedPreferences sp = getSharedPreferences("sliders", Activity.MODE_PRIVATE);
num_sliders = sp.getInt("sliders1", -1);
num_sliders = sp.getInt("sliders2", -1);
num_sliders = sp.getInt("sliders3", -1);
num_sliders = sp.getInt("sliders4", -1);
num_sliders = sp.getInt("sliders5", -1);
num_sliders = sp.getInt("sliders6", -1);
num_sliders = sp.getInt("sliders7", -1);
num_sliders = sp.getInt("sliders8", -1);
num_sliders = sp.getInt("sliders9", -1);
num_sliders = sp.getInt("sliders10", -1);
num_sliders = sp.getInt("bass_boost", -1);
return num_sliders;
}
Any help will be hugely appreciated as i need to get the apps update rolled out!
Thank you.

I know this is an old question, but I just wasted two hours on this, might as well give my answer in case anyone encounters the same problem.
What I had to do to have settings properly survive across app kills / device reboots was:
Use the editor to REMOVE the old value
Commit
Put the new value
Commit
So, for example:
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove(Constants.PREF_STARTED_EXPERIMENTS);
editor.commit();
editor.putStringSet(Constants.PREF_STARTED_EXPERIMENTS, experiments);
editor.commit();
Hope it saves someone some time.

The problem could be null values being saved into your preferences file. Please try if this answer solves your problem.

Related

SharedPreferences aren't resetting using remove(); or clear();

I'm trying to reset my SharedPreferences, but neither clear(), nor remove() work.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
editor = preferences.edit();
for (int t = 0; t < homeTiles.size(); t++) {
editor.remove(homeTiles.get(t).getmFunction() + "_tile_pos"); //this isnt running
editor.remove(homeTiles.get(t).getmFunction() + "_tile_vis"); //this is getting ecexuted
}
editor.apply();
I also checked the preference file and it did'nt change.
try this
for (int t = 0; t < homeTiles.size(); t++) {
editor.remove(homeTiles.get(t).getmFunction() + "_tile_pos").remove(); //this isnt running
editor.remove(homeTiles.get(t).getmFunction() + "_tile_vis").remove(); //this is getting ecexuted
}

How to reset counter?

I want to show Interstitial ads whenever the app reaches 10 launches. So i count them with
OnCreate{
prefs = getPreferences(Context.MODE_PRIVATE);
editor = prefs.edit();
totalCount = prefs.getInt("counter", 0);
totalCount++;
editor.putInt("counter", totalCount);
editor.commit(); }
and whenever totalCount = 10 i run the add:
if(totalCount==10){
fullScreenAd2.show();
}
Now i want to reset totalCount, how can i do this?
i know that calling totalCount++ adds 1 point and totalCount-- removes 1 point. But how can i reset it to 0?
I think you can just reset it to 0 after it becomes 10. For example:
if(totalCount==10){
fullScreenAd2.show();
totalCount=0; // and i think that, this should do it...
editor.putInt("counter", totalCount); // call editor to save
editor.commit(); //totalCount's value
}`
The following should work:
prefs = getPreferences(Context.MODE_PRIVATE);
editor = prefs.edit();
totalCount = prefs.getInt("counter", 0);
if(totalCount == 10){
fullScreenAd2.show();
totalCount = 0;
} else {
totalCount++;
}
editor.putInt("counter", totalCount);
editor.commit();

Using Shared Preferences for High Score saving

Hell I am trying to make highscore for my project but my code is only saving last value not highest value
How can I store only highest value? here is my code .
This is saving process ->
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
TextView outputView = (TextView)findViewById(R.id.textscore);
CharSequence textData = outputView.getText();
if (textData != null) {
editor.putString(TEXT_DATA_KEY, textData.toString());
editor.commit();
}
This is Reading process
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
String textData = prefs.getString(TEXT_DATA_KEY, "No Preferences!");
TextView outputView = (TextView) findViewById(R.id.textread);
You need to check the previously saved value to see which is highest else it you will just save the latest value, not the highest
E.g.
if (textData != null) {
int score = Integer.parseInt(textData.toString());
if(score > prefs.getInt(TEXT_DATA_KEY, 0)) // Or get String, with parse Int.
{
//editor.putString(TEXT_DATA_KEY, textData.toString()); // Should be saved as int
editor.putInt(TEXT_DATA_KEY, score);
editor.commit();
}
}
You need to store a new value only if the existing value in shared preferences is lesser than the new value.
You don't seem to be having this value check in your code
Replace
if (textData != null) {
editor.putString(TEXT_DATA_KEY, textData.toString());
editor.commit();
}
with
if (textData != null) {
if(Integer.parseInt(prefs.getString(TEXT_DATA_KEY, "0")) < Integer.parseInt(outputView.getText())) {
editor.putString(TEXT_DATA_KEY, textData.toString());
editor.commit();
}
}
First of all why are you saving high scrore as string, use int or float (if you must).
The simplest way is to read high score before saving it and compare to the one you try to save.
You'll want to keep track of your in-game high score. That's easiest done using a number rather than using a text view's string:
int hiScore = 0;
In your startup, perhaps in onCreate(), you'll want to obtain the previous high score:
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
try {
hiScore = prefs.getInt(HI_SCORE, 0);
} catch (NumberFormatException e) {
hiScore = 0;
}
When a new score is obtained, you'll want to record it if it's higher than the previous high score:
if (newScore > hiScore) {
hiScore = newScore;
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(HI_SCORE, hiScore);
editor.commit();
}

Android: SharedPreferences Issue (Multiple SharedPreferences)

I have multiple SharedPreferences that are each storing one int value each. I have successfully created multiple SharedPreferences before, but I am trying a slightly different approach for this one. I am only keeping the highest 5 values. I am getting each value from its SharedPreference, then I am adding the 5 values + the current value I want to compare against the others in an ArrayList. I am calling the reverse sort method on it, then I am removing the last value (because it is extra). I am then putting each index into the editor of the SharedPreferences. Here is what I have:
prefs1 = this.getSharedPreferences("key1", Context.MODE_PRIVATE);
int value1 = prefs1.getInt("number1", 0);
prefs2 = this.getSharedPreferences("key2", Context.MODE_PRIVATE);
int value2 = prefs2.getInt("number2", 0);
prefs3 = this.getSharedPreferences("key3", Context.MODE_PRIVATE);
int value3 = prefs3.getInt("number3", 0);
prefs4 = this.getSharedPreferences("key4", Context.MODE_PRIVATE);
int value4 = prefs4.getInt("number4", 0);
prefs5 = this.getSharedPreferences("key5", Context.MODE_PRIVATE);
int value5 = prefs5.getInt("number5", 0);
ArrayList<Integer> numList = new ArrayList<Integer>();
Collections.addAll(numList, value0, value1, value2, value3, value4, value5);
Collections.sort(numList, Collections.reverseOrder());
numList.remove(numList.size()-1);
value1 = numList.get(0);
value2 = numList.get(1);
value3 = numList.get(2);
value4 = numList.get(3);
value5 = numList.get(4);
Editor editor = prefs1.edit();
editor.putInt("number1", value1);
editor.commit();
editor = prefs2.edit();
editor.putInt("number2", value2);
editor.commit();
editor = prefs3.edit();
editor.putInt("number3", value3);
editor.commit();
editor = prefs4.edit();
editor.putInt("number4", value4);
editor.commit();
editor = prefs5.edit();
editor.putInt("number5", value5);
editor.commit();
The problem I am having is that is showing 0s for each one of the values in my other activity even after value0 is positive after it executed through.
Is there anything wrong with how I am doing this? (If not then it must be when I get these values in another activity, but I am almost positive I have that right.)
EDIT*
Perhaps it is in the retrieval, here is from the retrieving activity:
prefs1 = this.getSharedPreferences("key1", Context.MODE_PRIVATE);
num1 = prefs1.getInt("number1", 0); //0 is the default value
tv1 = (TextView) findViewById(R.id.val1);
tv1.setText(String.valueOf(num1));
prefs2 = this.getSharedPreferences("key2", Context.MODE_PRIVATE);
num2 = prefs2.getInt("number2", 0); //0 is the default value
tv2 = (TextView) findViewById(R.id.val2);
tv2.setText(String.valueOf(num2));
prefs3 = this.getSharedPreferences("key3", Context.MODE_PRIVATE);
num3 = prefs3.getInt("number3", 0); //0 is the default value
tv3 = (TextView) findViewById(R.id.val3);
tv3.setText(String.valueOf(num3));
prefs4 = this.getSharedPreferences("key4", Context.MODE_PRIVATE);
num4 = prefs4.getInt("number4", 0); //0 is the default value
tv4 = (TextView) findViewById(R.id.val4);
tv4.setText(String.valueOf(num4));
prefs5 = this.getSharedPreferences("key5", Context.MODE_PRIVATE);
num5 = prefs5.getInt("number5", 0); //0 is the default value
tv5 = (TextView) findViewById(R.id.val5);
tv5.setText(String.valueOf(num5));
You can think of SharedPreferences like a giant map for all your stuff, but unless you are doing anything funky, you should store and retrieve data from the same giant map (i.e. the same SharedPreferences). What you are doing is creating named shared preferences. I would recommend just using the default. If you are curious to learn more about what that means check out this question.
So, in your case if you are storing 5 values, you can do so within the same SharedPreferences by just supplying different keys as follows:
SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor mSharedPreferencesEditor = mSharedPreferences.edit();
mSharedPreferencesEditor.putInt("numberX", numberX);
mSharedPreferencesEditor.putInt("numberY", numberY);
mSharedPreferencesEditor.commit()
mSharedPreferences.getInt("numberX", numberX);
mSharedPreferences.getInt("numberY", numberY);
You can easily get and put with different keys into the same sharedPrefs. Your code would become:
SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor mSharedPreferencesEditor = mSharedPreferences.edit();
int value1 = mSharedPreferences.getInt("number1", 0);
int value2 = mSharedPreferences.getInt("number2", 0);
int value3 = mSharedPreferences.getInt("number3", 0);
int value4 = mSharedPreferences.getInt("number4", 0);
int value5 = mSharedPreferences.getInt("number5", 0);
...
mSharedPreferencesEditor.putInt("number1", value1);
mSharedPreferencesEditor.putInt("number2", value2);
mSharedPreferencesEditor.putInt("number3", value3);
mSharedPreferencesEditor.putInt("number4", value4);
mSharedPreferencesEditor.putInt("number5", value5);
mSharedPreferencesEditor.commit();
Your issue concerning all your values being 0 may be different. I would fully expect all your calls to getInt to be 0 because you are never storing anything but 0 in the sharedPrefs. It looks like you are just adding zeros and putting zeros. I am not sure what you are trying to do here, but it sure would help to, at some point before calling this function, assign numbers 1-5 to something other than 0 by calling mSharedPreferencesEditor.putInt(number); on a sharedPrefs object like so:
SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor mSharedPreferencesEditor = mSharedPreferences.edit();
//for example, for the key "number5"
mSharedPreferencesEditor.putInt("number5", value5);

How to store one string and arrayvalue in sharedpreference?

I have array values of up[]={0,0,0,0,0} and view="adult" thesetwo value i want to store and retrieve in from sharedpreference how to do that...
Assuming that you have a list of preferences for you app called MY_PREFS, I'd do this:
SharedPreferences settings = getSharedPreferences(MY_PREFS, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("arrayLength",up.size());
for(int i=0; i<up.size(); i++){
editor.putInt("up"+String.valueOf(i), up[i]);
}
editor.putString("view", "adult");
To retrieve them do:
SharedPreferences settings = getSharedPreferences(MY_PREFS, 0);
int arraySize = settings.getInt("arrayLength");
int up[] = new int[arraySize];
for(int i=0; i<arraySize; i++){
up[i] = settings.getInt("up"+String.valueOf(i));
}
String view = settings.getString("view");
you can do by simple way, like this
SharedPreferences settings = getSharedPreferences("pref_name", 0);
SharedPreferences.Editor editor = settings.edit();
String values="";
for(int i=0; i<yourArray.length; i++){
values+=","+Integer.toString(yourArray[i]);
}
editer.putString("array",values);
editor.putString("view", "adult");
To get those values,
SharedPreferences settings = getSharedPreferences("pref_name", 0);
String[] strArray=settings.getString("array").split(",");
int[] yourArray=new int[strArray.length];
for(int i=0;i<strArray.length;i++){
yourArray[i]=Integer.toParseInt(strArray[i]);
}
Well as far as I have seen you can't directly store an array in shared preferences. You can however use a for loop to save an int with an increasing name and have it call it back the same way when you need it and store it into another array.
for(int i=0; i<numInYourArray; i++){
editor.putInt("up"+i, up[i]);
}
If you aren't sure on how to use Shared Preferences in general look here

Categories

Resources