0

I need to extract the application data using SharedPreferences in Xamarin.Android.

Here is what I have tried in android.

public static void SetAuthentication(bool authenticationValue)
    {
        var localSettings = Application.Context.GetSharedPreferences ("Hello", FileCreationMode.Private);
        localSettings.Edit ().PutBoolean ("ValidUser", authenticationValue).Commit ();

    }

    public static bool GetAuthentication()
    {
        var retValue = false;
        object value;
        var localSettings = Application.Context.GetSharedPreferences ("Hello", FileCreationMode.Private);
        localSettings.GetBoolean ("ValidUser", out value);
    }

But somehow I feel this is not the right approach. Any guidance is appreciated. Thanks

poupou
  • 43,413
  • 6
  • 77
  • 174
user2625086
  • 221
  • 5
  • 18

2 Answers2

0

On the Android platform, preferences are stored in a text file in the private folders of the Android application - there are 2 ways to access these SharedPreferences data files.

You can either use the "default" file for the application, or you can use a named file, using any name you want.

This second approach is what you have chosen to do by calling GetSharedPreferences with a filename.


I would suggest to just use the "default" preferences. This way has some advantages:

  • the code is simpler
  • the preferences can be accessed more easily in a PreferenceActivity later on

To do this, create your ISharedPreferences instance using:

ISharedPreferences localSettings = 
        PreferenceManager.GetDefaultSharedPreferences (mContext); 

Once you have your "default" shared preferences in this manner, the rest of your code stays the same.


For more info, check out related questions:

Community
  • 1
  • 1
Richard Le Mesurier
  • 29,432
  • 22
  • 140
  • 255
0

I agree with Richard so just to be clear and complete I would do like this:

public static void SetAuthentication(Context ctx, bool authenticationValue)
{
    ISharedPreferences pref = ctx.GetSharedPreferences("your_app_preferences", FileCreationMode.Private);
    ISharedPreferencesEditor edit = pref.Edit();
    edit.PutBoolean("ValidUser", authenticationValue);
    return edit.Commit();
}

public static bool GetAuthentication(Context ctx)
{
    ISharedPreferences pref = ctx.GetSharedPreferences("your_app_preferences", FileCreationMode.Private);
    return pref.GetBoolean("ValidUser"), null);
}

I hope this will make you feel happier.

Daniele D.
  • 2,624
  • 3
  • 36
  • 42