-1

What I want to do is I want to maintain a profile pic for my user in my app. The user can pic from the local Pictures library. So whenever the app loads it should check in local app data whether a pic is there or not, if exists it should set the image to it. I tried doing like this but it isn't working.

// Saving
BitmapImage bitmapImage = image.Source as BitmapImage;
Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
string path = bitmapImage.UriSource.ToString();
localSettings.Values["ProfilePic"] = path;

// In constructor retrieving like this.
string sourceVal = localSettings.Values["ProfilePic"] as string;

if (sourceVal != null) {
    Image img = new Image();
    BitmapImage bi = new BitmapImage();
    Uri uri = new Uri(sourceVal);
    bi.UriSource = uri;
    img.Source = bi;
}

It's throwing exceptions, can anyone give em the appropriate code using C#?

System.NullReferenceException occurred.

Tim
  • 27,313
  • 8
  • 59
  • 71
Anurag
  • 23
  • 1
  • 6
  • 1
    What line is the error occurring on? – Tim Jun 12 '15 at 04:37
  • possible duplicate of [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) – Tim Jun 12 '15 at 04:38

1 Answers1

0

Modified you code here and there and its working fine for me. Have a look

xaml

    <Image Name="img" Height="100" Width="100"/>

Code behind:

// define on top
Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;


//in constructor or in OnNavigatedTo()
 string sourceVal = localSettings.Values["ProfilePic"] as string;
 if (sourceVal != null)
        {
            //  Image img1 = new Image();
            BitmapImage bi = new BitmapImage();
            Uri uri = new Uri(sourceVal, UriKind.Relative);
            bi.UriSource = uri;
            img.Source = bi;
        }
        else
        {
            // hardcoding image source for testing. You can set image here from gallery
            img.Source = new BitmapImage(new Uri("/Assets/AlignmentGrid.png", UriKind.Relative));
        }

// Save image (in OnNavigatedFrom())
BitmapImage bitmapImage = img.Source as BitmapImage;
string path = bitmapImage.UriSource.ToString();
localSettings.Values["ProfilePic"] = path;

Try this and let me know if any issue.

Nishi
  • 614
  • 4
  • 17