How to fix System.NullReferenceException: 'Object reference not set to an instance of an object.'

Andreea 0 Reputation points
2024-01-09T17:42:26.8866667+00:00

I'm encountering 'System.NullReferenceException' while working on a .NET MAUI application. The exception occurs during saving, deleting, and when navigating back to view all recipes. There isn't any particular line of code that seems to be associated with the exception. What could be the cause of this issue, and how can I fix it? Here's a snippet of my code:

using Microsoft.Maui.Controls;
using proiect2_v2.Models;
using System;
using System.IO.Compression;
using SixLabors.ImageSharp;
using System.IO;
using System.Threading.Tasks;

namespace proiect2_v2
{
    public partial class RecipePage : ContentPage
    {
        public RecipePage()
        {
            InitializeComponent();
            CheckAndRequestStoragePermission();
        }

        async void CheckAndRequestStoragePermission()
        {
            try
            {
                var status = await Permissions.CheckStatusAsync<Permissions.StorageWrite>();

                if (status != PermissionStatus.Granted)
                {
                    var result = await Permissions.RequestAsync<Permissions.StorageWrite>();

                    if (result != PermissionStatus.Granted)
                    {
                        Console.WriteLine("StorageWrite permission denied");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception: {ex.Message}");
            }
        }

        async void OnSelectImageButtonClicked(object sender, EventArgs e)
        {
            try
            {
                var mediaOptions = new MediaPickerOptions
                {
                    Title = "Select Image"
                };

                var selectedImage = await MediaPicker.PickPhotoAsync(mediaOptions);

                if (selectedImage != null)
                {
                    var bytes = await ImageToBytes(selectedImage);
                    if (bytes != null)
                    {
                        SetRecipeImage(bytes);
                    }
                    else
                    {
                        Console.WriteLine("Failed to convert image to bytes.");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception in OnSelectImageButtonClicked: {ex.Message}");
            }
        }

        async Task<byte[]> ImageToBytes(FileResult image)
        {
            using (var stream = await image.OpenReadAsync())
            using (var memoryStream = new MemoryStream())
            {
                await stream.CopyToAsync(memoryStream);
                return memoryStream.ToArray();
            }
        }

        async void SetRecipeImage(byte[] bytes)
        {
            ((Recipe)BindingContext).ImageData = bytes;
            recipeImage.Source = ImageSource.FromStream(() => new MemoryStream(bytes));
        }

        async void OnSaveButtonClicked(object sender, EventArgs e)
        {
            try
            {
                var recipe = (Recipe)BindingContext;

                if (TryGetSelectedImagePath(out var imagePath))
                {
                    recipe.ImageData = File.ReadAllBytes(imagePath);
                }
                else
                {
                    Console.WriteLine("No image selected.");
                }

                await App.Database.SaveRecipeAsync(recipe);
                BindingContext = await App.Database.GetRecipeAsync(recipe.Id);
                await Navigation.PopAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Save button exception: {ex.Message}");
            }
        }

        bool TryGetSelectedImagePath(out string imagePath)
        {
            imagePath = (recipeImage.Source as FileImageSource)?.File;
            return !string.IsNullOrEmpty(imagePath);
        }

        async void OnDeleteButtonClicked(object sender, EventArgs e)
        {
            var recipe = (Recipe)BindingContext;
            await App.Database.DeleteRecipeAsync(recipe);
            await Navigation.PopAsync();
        }

        async void OnChooseButtonClicked(object sender, EventArgs e)
        {
            await Navigation.PushAsync(new IngredientPage((Recipe)this.BindingContext)
            {
                BindingContext = new Ingredient()
            });
        }

        protected override async void OnAppearing()
        {
            base.OnAppearing();

            try
            {
                if (BindingContext is not Recipe recipe)
                {
                    return;
                }

                if (recipe.ImageData != null)
                {
                    SetRecipeImage(recipe.ImageData);
                }

                if (recipe.Id != 0)
                {
                    BindingContext = await App.Database.GetRecipeAsync(recipe.Id);
                    recipe = (Recipe)BindingContext;

                    if (recipe.ImageData != null)
                    {
                        SetRecipeImage(recipe.ImageData);
                    }

                    recipeView.ItemsSource = await App.Database.GetRecipeIngredientsAsync(recipe.Id);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception in OnAppearing: {ex.Message}");
            }
        }
    }
}

Here is the Call Stack:
Screenshot 2024-01-09 224559

Developer technologies .NET .NET MAUI
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.