jamesmontemagno / SettingsPlugin

Read and Write Settings Plugin for Xamarin and Windows
MIT License
324 stars 80 forks source link

Xamarin.Forms Android Previewer breaks when accessing Settings in Constructor #62

Closed renzska closed 7 years ago

renzska commented 7 years ago

Bug

Xamarin.Forms Android Previewer breaks when accessing Settings in Constructor.

Version Number of Plugin: 2.5.4 Device Tested On: None Simulator Tested On: Xamarin.Forms Previewer

Expected Behavior

The form previewer renders the page.

Actual Behavior

The form previewer fails to render the page. I get an exception in the Xamarin.Forms Previewer:

Steps to reproduce the Behavior

An example setting:

private const string AcceptedTermsOfUseKey = "AcceptedTermsOfUse_Key";
        private static readonly bool AcceptedTermsOfUseDefault = false;

        public static bool AcceptedTermsOfUse
        {
            get
            {
                return AppSettings.GetValueOrDefault<bool>(AcceptedTermsOfUseKey, AcceptedTermsOfUseDefault); //errors on this line
            }
            set
            {
                AppSettings.AddOrUpdateValue<bool>(AcceptedTermsOfUseKey, value);
            }
        }

Stacktrace:

image

Feature Request:

This works on iOS but fails on Android. Having this work on Android without having to try/catch all of my settings would be great.

Thank!

John

renzska commented 7 years ago

It breaks on this line:

https://github.com/jamesmontemagno/SettingsPlugin/blob/0656d582f458d7a7d37635489ce0ee44b209a405/src/Plugin.Settings.Android/Settings.cs#L33

Not sure if a try/catch is the best way to approach this. On the iOS side, it grabs the NSUserDefaults.StandardUserDefaults successfully, and when grabbing they key, returns a null which then returns the default value:

https://github.com/jamesmontemagno/SettingsPlugin/blob/master/src/Plugin.Settings.iOSUnified/Settings.cs#L28

renzska commented 7 years ago

Looking into it a little more, I'm guessing Application.Context might actually be null which we could use to return defaults. I'll try pulling down the code and creating a PR.

renzska commented 7 years ago

Alright. I tested my theory out and it worked. I've submitted a PR here: https://github.com/jamesmontemagno/SettingsPlugin/pull/63 against your value checks branch. Let me know if you'd rather have it against the master.

Thanks!

jamesmontemagno commented 7 years ago

Will be fixed in 3.0, no longer taking changes to 2.x