Setting User Preferences in Android
android, application-settings, xamarin
Solution
You can. But it isnt just something like setBoolean().
you have to to it like this:
_sharedPref.Edit().PutBoolean("key","value").Commit();
// or
_sharedPref.Edit().PutBoolean("pref_myPref", true).Commit();
Problem
I'm using Xamarin and starting the process of converting an iOS app into an Android app and I've hit a snag with retrieving and setting preferences. In iOS I'd just get a `NSUserDefaults` by using `NSUserDefaults.StandardUserDefaults` and then I could get a `bool` with `BoolForKey` and set it with `SetBool`. However, I can't quite find equivalents with Android. In Android I setup a Preferences.xml file like this: ``` <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <CheckBoxPreference android:key="pref_myPref" android:title="My Bool Pref" android:summary="A Boolean Preference" android:defaultValue="true"/> </PreferenceScreen> ``` And then I can do this: ``` private ISharedPreferences _sharedPref = PreferenceManager.GetDefaultSharedPreferences(Setup.GetApplicationContext()); ``` Where `Setup.GetApplicationContext` is a static method that returns the context I saved when creating `Setup` and then I can get my preference with: ``` _sharedPref.GetBoolean("pref_myPref", true); ``` But `ISharedPreferences` doesn't have any `Set...` functions?!? How can I, in code, set a preference? This is part of an MVVMCross application and the settings code is supposed to live at the level of the view models (the IoC container will supply Android or iOS versions of a `Settings` service as appropriate), so I don't want to handle it in a view. I'm trying to keep it abstract. I've been looking at this: http://developer.android.com/guide/topics/ui/settings.html But I'm having a hard time translating into Xamarin C# code and making it work the way I want it to. I want to be able to get back an instance of my `CheckBoxPreference` so I can set the damn thing without creating an Activity or view.