Skip to main content

Abstracting Xamarin Android SharedPreferences

The standard way to get/set SharedPreferences in Xamarin is with the following code.

Get Preference:


 var shared = con.GetSharedPreferences(_preferenceName, FileCreationMode.WorldReadable);
 var value = shared.All.Where(x => x.Key == key).FirstOrDefault().Value;

Set Preference:


var shared = con.GetSharedPreferences("PreferenceName", FileCreationMode.WorldWriteable);
            var edit = shared.Edit();
            edit.PutString(key, val);
            edit.Commit();

The main issue I have/had with this is you often have to know what will be returned, and what type you need to save as. Usually this isn't difficult, but it adds an un-needed level of complexity.

The other major issues I have with this, is that it is quite verbose, and unnecessary. The code duplication here can be quite high.

Continue Reading

See all tags.