I have an Android application in which I have my preferences in an XML file, which works fine. I now want to set one of the preferences using code instead of displaying the entire preference screen, how would I go about doing this?
Android – How Do I Set A Preference In Code
androidandroid-preferencessharedpreferences
Related Question
- Android – R cannot be resolved – Android error
- Android – Fling gesture detection on grid layout
- Android – How to close/hide the Android soft keyboard programmatically
- Android – How to install an APK file in the Android emulator
- Android “Only the original thread that created a view hierarchy can touch its views.”
- Java – Proper use cases for Android UserManager.isUserAGoat()
- Android 8: Cleartext HTTP traffic not permitted
Best Solution
I assume by preferences you are referring to your application's preferences and not Android phone settings.
To store preferences between runs of you application you need to do the following
Create a SharedPreferences object
String n identifies your preferences and the second argument is the mode they'll be accessed
Instantiate an Editor object
Note: do not try settings.editor.edit(), this will not make a persistent object and the code below will not work
Write your preferences to the buffer
There are numerous put function, putString, putBoolean, etc. The String is the key ("version", "good run") and the value is the value ("1.5.2", true)
Flush the buffer
This actually writes you put to the preferences. If your app crashes before this line then the preferences will not be written. There is also a documented bug: commit() is supposed to return a boolean indicating success or failure. Last I checked it always returned false.
These preferences will by stored on the phone and will only be accessible to your application.
More documentation is here