Hi all - I’m trying to use SharedPreferences in my...
# android
w
Hi all - I’m trying to use SharedPreferences in my app in order to save a few preferences that then need to update pretty instantaneously inside the app. I have a settings page, where the user can switch from light to dark mode, and also update the voice of a TTS functionality. When the user ‘saves changes’ - I call editor.putXXXX(key, value).apply() for each setting and then close out of the settings page. Unfortuntately, I neither see the settings changed in my main activity, nor see the updated settings when I go back into the settings page. I understand that .apply() is asynchronous - I suspect that calling .apply() for each setting is going to cancel previous calls to .apply() - am I able to make several “puts” and then call .apply() just the once to make those several changes in one go? Why would I not see immediate changes in my main activity even if I call ‘sharedPrefs.getXXX’ again? I’m assuming it’s just an issue whereby the apply() function hasn’t actually finished yet? I’ve tried Googling and SOing for solutions but not getting anywhere (edited)
Would I only need 1 call to commit even if I make several .put calls?
r
w
Yeah I saw that - I think I need the immediacy of commit, unless there’s a nice way to handle an async call like apply so that I can wait until it’s applied before moving on?
i
You absolutely don't need
commit()
.
apply()
is only about asynchronously writing to disk. The in memory shared preferences that it maintains is immediately updated
👍 1
w
Ok great, thanks @Ian Lake. I have a usecase whereby two putBooleans may get called one straight after the other. At the moment, it looks like it’s ignoring the second. Ie:
Copy code
editor.putString('String', 'newVal')
editor.putBoolean("val 1", false)
editor.putBoolean("val 2", false)

editor.apply()
running this, the val 2 doesn’t change, the first two do
i
Sounds like a good stack overflow question that shows your code where you write and read the shared preferences
w
Turns out I was being an idiot, passing in the old value not the new one 🙄