Tutorials Xamarin SharedPreferences Example in Xamarin Android

SharedPreferences Example in Xamarin Android

Shared preferences are persistence key/value data pairs, used to store primitive data pairs such as bool, float, int, string and long. The data saved into android preference are persisted across different user sessions and is private to the application it is created. Any other application cannot access it.

For using shared preference to saving data pairs, you need first get an instance of ISharedPreferences interface. A shared preference can be specific to an activity or made global to all activities in the application. If you want to create a single preference file specific to an activity you can use Activity.GetPreferences to initialize ISharedPreferences interface. For getting the application level preference, you can call GetSharedPreferences method passing the preference name and mode of operation.

ISharedPreferences prefs = Application.Context.GetSharedPreferences ("PREF_NAME", FileCreationMode.Private);

Now let us call Edit() to get an instance of ISharedPreferencesEditor. This batches all of the changes made to value in shred preferences and saves only when there is a call to Commit() or Apply() is made.

ISharedPreferencesEditor editor = prefs.Edit();
editor.PutInt("your_key1" ,10);
editor.PutString("your_key2", "Xamarin Example");
editor.Apply();

To read values from shared preferences, we can use methods such as GetString(), GetInt(), GetFloat() etc. by providing proper key. The following snippets retrieves the values stored in the above step.

var value1 = prefs.GetInt ("your_key1", 0);
var value2 = prefs.GetString ("your_key2", null);
Total
0
Shares
guest
4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Kunal Prajapati
Kunal Prajapati
6 years ago

how to change the background color of the entire app through settings activity

Kunal Prajapati
Kunal Prajapati
6 years ago

how to change the background color of the entire app through settings activity

Tom
Tom
4 years ago

To maintain use’s section

Tom
Tom
4 years ago

rgrgrgrg

Previous Post

Google has Recently Released Beta Version of a Publisher Plugin for WordPress

Next Post
Google IO2015

Android M – Feature Highlights in the Next Major Android Release

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
4
0
Would love your thoughts, please comment.x
()
x