I want to save and retrieve some application settings in my Xamarin.Android project.
I know that in Android (java), I use the class SharedPreferences
to store this information, but I do not know how to convert that to Xamarin C#.
When I type "SharedPreferences" into the Xamarin Studio IDE, there is no auto-completion, so I don't know what to use.
An initial search of the interwebs took me to a related question, but only contains Android java:
So to summarise:
SharedPreferences
?Android App Development for BeginnersShared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.
A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared. This page shows you how to use the SharedPreferences APIs to store and retrieve simple values.
Android Shared Preferences Overview Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment.
These preferences will automatically save to SharedPreferences as the user interacts with them. To retrieve an instance of SharedPreferences that the preference hierarchy in this activity will use, call getDefaultSharedPreferences(android. content. Context) with a context in the same package as this activity.
The Xamarin.Android equivalent of SharedPreferences
is an interface called ISharedPreferences
.
Use it in the same way, and you will be able to easily port Android code across.
For example, to save a true/false bool
using some Context
you can do the following:
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (mContext); ISharedPreferencesEditor editor = prefs.Edit (); editor.PutBoolean ("key_for_my_bool_value", mBool); // editor.Commit(); // applies changes synchronously on older APIs editor.Apply(); // applies changes asynchronously on newer APIs
Access saved values using:
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (mContext); mBool = prefs.GetBoolean ("key_for_my_bool_value", <default value>); mInt = prefs.GetInt ("key_for_my_int_value", <default value>); mString = prefs.GetString ("key_for_my_string_value", <default value>);
From this sample, you can see that once you know the correct C# interface to use, the rest is easy. There are many Android java examples on how to use SharedPreferences
for more complex situations, and these can be ported very easily using ISharedPreferences
.
For more information, read this thread:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With