Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
62 views
in Technique[技术] by (71.8m points)

How do I use SharedPreferences in Xamarin.Android?

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:

  • What is the Xamarin Android C# equivalent of Android Java's SharedPreferences?
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...