0

I have a problem with Save and Load Settings in Universal Apps. I type this code:

enter class Setting
{
    public static Kolor Read()
    {
        var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

        byte _red = (byte)localSettings.Values["R"];
        byte _green = (byte)localSettings.Values["G"];
        byte _blue = (byte)localSettings.Values["B"];

        return new Kolor(_red, _green, _blue);
    }

    public static void Save(Kolor kolor)
    {
        var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
        localSettings.Values["R"] = kolor.R;
        localSettings.Values["G"] = kolor.G;
        localSettings.Values["B"] = kolor.B;
    }
}

When I try to start apps, debuger show me NullReferenceException in:

enter byte _red = (byte)localSettings.Values["R"];

Someone can help me?

Soner Gönül
  • 91,172
  • 101
  • 184
  • 324
zeed94
  • 111
  • 1
  • 1
  • 8
  • Related: [What is a `NullReferenceException` and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Soner Gönül Apr 22 '15 at 06:19

1 Answers1

1

I think your issue is coming from the value that does not exist in the LocalSettings, so first check it exists.

public static Kolor Read()
{
    byte _red = GetByte("R");
    byte _green = GetByte("G");
    byte _blue = GetByte("B");

    return new Kolor(_red, _green, _blue);
}

private static byte GetByte(string key)
{
     if (!ApplicationData.Current.LocalSettings.Values.ContainsKey(key))
     {
         return default(byte);
     }
     return (byte)(ApplicationData.Current.LocalSettings.Values[key]);
}
Barnstokkr
  • 2,086
  • 15
  • 33