SharedPreferences overwrites another value

I have a problem with SharedPreferences if I want to keep two different values. I tried with this code:

 SharedPreferences sharedPref = getSherlockActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt(getString(R.string.SavedStartSilentHour), hour); editor.commit(); editor.putInt(getString(R.string.SavedStartSilentMinute), min); editor.commit(); // One editor.commit() is enough 

If I run this code, the first value will be overwritten by the seccond value. If I do the second part, the value will be saved correctly. Why is this?

+4
source share
3 answers

Your code seems perfect!

You could simplify this thing by doing all this after all the "puts" operations. Although I do not think this may be your problem ...

Just make sure that the defined SavedStartSilentHour and SavedStartSilentMinutes xml values SavedStartSilentHour defined correctly, that is, if they match, they will of course be overwritten. (This is the only thing that makes sense for me to consider your code).

Let everyone know about your progress;)

+3
source

Delete the first call

 editor.commit(); 

and all will be well.

0
source

The problem is most likely caused by reusing the key, so the second assignment simply overwrites the same value.

One way to test this hypothesis is to try using simple keys that eliminate this possibility, for example:

 editor.putInt("hour", hour); editor.putInt("min", min); 

Alternatively, you can track the debugger, and the results of getString(keyId) can be compared.

If this really SavedStartSilentHour problem, make sure that the SavedStartSilentHour and SavedStartSilentMinute actually being evaluated for different lines - check the resource file itself.

0
source

Source: https://habr.com/ru/post/1487380/


All Articles