What is shared preferences

The Xamarin android application provides so many ways to store the data within an application. The one of the most used is the Shared preference. Shared preference provides a way to store data within an application in the form of key and value.

And the most commonly used is sqlite. The sqlite provides a way to store data in the form of tables which can store a large amount of data within an application but the main problem with sqlite is that it needs a lot of coding required to store the data .

But the Shared preference doesn't need a lot code to store the data. It need just a key and pair value to store and retrieve data. But the main problem with shared preference is that it can't store the large amount of data in an application.

Suppose you want to store the flag value of an application that application needs every time when start then shared preference help to get the data . The value of an shared preference exist even if the application kills or the application is in background state and when an device shut down.

Store data in Shared Preferences in Xamarin Android :

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

ISharedPreferencesEditor editor = prefs.Edit();
editor.PutString("userid", "12345"); /* "userid is key" and "12345" is value*/
editor.PutString("usertype", "Doctor");
editor.PutString("UserName","XamarinAndroid");
editor.Apply();


Retrieve data using Shared Preferences in Xamarin Android :


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

string userid= prefs.GetString("usertype", "");
/*usertype is the key used to get the value based on that key which
you have store earlier , "" is the default value you can get if the
value is not present*/
Int64 value1 = Convert.ToInt64(prefs.GetString("userid", "0"));


Remove all shared preference value

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

prefs.Edit.Clear.Commit();


Remove specific shared preference value using Key

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

prefs.Edit.Remove("shared_pref_key").Commit();

1 comment: