Could not save pictures into db with Maui and SQlite Episode1

Outline

I am creating file manager software with Maui and SQlite, so I reworked this page project

.NET MAUI アプリで SQLite を使用してローカル データを格納する - Training | Microsoft Learn

- YouTube*1

and save pictures into the db.
However, I cannot save pictures into the db also Listview does not show list.
Then, I ask a question in Teratail and StackOverflow.

 Honestly, you can understand the error easily in these page than this blog . I wrote this page for my memorization

Problem Overview

What you are trying to do: I am trying to save image binary data into a SQLite database named gazouByte.db3 when the "Save" button is pressed after selecting an image file using a file picker. Additionally, I want to display the list of saved images, including their "Id," "File Name," and "Extension," in a CollectionView on the MainPage when the "Get All GazouList" button is pressed. What issue you are facing: The image binary data is not being saved to the gazouByte.db3 database. When clicking the "Get All GazouList" button, only "got all file list" is displayed, and the "Id," "File Name," and "Extension" are not shown. Note that the table gazouByte has been confirmed to be created using "DB Browser for SQLite."

 

  • Expected Behavior

    When starting debugging, a table named gazouByte should be created in the app data. After selecting an image using the file picker, the selected image should be previewed under "Select File." When clicking the "Save File" button, the image data should be saved into the gazouByte.db3 database. Clicking the "Get All GazouList" button should display the "Id," "File Name," and "Extension" of the saved images in the CollectionView.

  • What I Have Tried

    Verified that exception handling in GazouByteRepositry.AddNewGazouByte method is correctly implemented. Confirmed that the table gazouByte is created using "DB Browser for SQLite." Noticed that a System.NullReferenceException occurs when pressing the "Save File" button again without selecting a new image.

  • Error Messages and Logs

    No error messages are displayed, but the image data is not saved.

  • Environment

    Windows 11 Home 23H2 Visual Studio Community 2022 Preview 17.11.0 Preview 4.0 Microsoft.Maui.Controls 8.0.80 Microsoft .NET SDK 8.0.107 (x64) SQlitePCLRaw.bundle_green 2.1.9 sqlite-net-pcl 1.9.172 CommunityToolkit.Mvvm 8.2.2

    db at DBbrowser

 

The question pages

Causing

 Reason for not saving into db

  • The project had created db dupulicately that's why picture was not saved

  • MainviewModel recreated another db even db had already created at MauiProgram.cs, so pictures were not saved correct path.

  •  

    namespace WorkReview
    {
    public static class MauiProgram
    {
    public static MauiApp CreateMauiApp()
    {
    var builder = MauiApp.CreateBuilder();
    builder
    .UseMauiApp<App>()
    .ConfigureFonts(fonts =>
    {
    fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
    fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
    });
    string dbPath = FileAccessHelper.GetLocalFilePath("gazouByte.db3");
    builder.Services.AddSingleton< GazouByteRepositry> (s => ActivatorUtilities.CreateInstance< GazouByteRepositry> (s, dbPath));//Creating db as instance at App folder.

    ↑ here

    return builder.Build();
    }
    }
    }

      • using System;
        using System.Collections.Generic;
        using System.Collections.ObjectModel;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;
        using CommunityToolkit;
        using CommunityToolkit.Mvvm.ComponentModel;
        using WorkReview.Models;

        namespace WorkReview.ViewModels
        {
        public partial class MainViewModel : ObservableObject
        {
        private GazouByteRepositry _gazouByteRepositry;

        public MainViewModel()
        {
        _gazouByteRepositry = new GazouByteRepositry("gazouByte.db3");

        //↑ Create duplicately db at here
        }

        [ObservableProperty]
        public string gazouName;

        [ObservableProperty]
        public string gazouPath;
        [ObservableProperty]
        public byte gazouBinary;
        [ObservableProperty]
        public string gazouExtension;


        public void SaveGazouToDataBase()//MainPageから渡された画像データをRepositryへ送る。
        {
        var gazouByte = new GazouByte
        {
        GazouName = gazouName,
        GazouBinary = gazouBinary,
        GazouExtension = gazouExtension

        };

        _gazouByteRepositry.AddNewGazouByte(GazouName, GazouBinary, GazouExtension);

        }

        }
        }

      Solutions

      I deleted the line and insert picture data directly into dbPath throw App.GazouByteRepo."MethodName" .

          • namespace WorkReview.ViewModels;

            public partial class MainViewModel : ObservableObject
            {


            [ObservableProperty]
            private string? statusMessage;

            [ObservableProperty]
            private List<GazouByte>? gazouBytes; //MainPageのListView用のリスト。ListViewにはC#側にリストを作る必要がある。

            [ObservableProperty]
            private ImageSource? userPreview; //MainPageのプレビュー用


            private string? gazouName; //ファイル名

            private byte? gazouBinary; //画像のバイナリデータ

            private string? gazouExtension; //拡張子情報


            public MainViewModel()
            { }

            [RelayCommand]
            private void OnGetAllGazou() //画像リストの取得ボタン
            {
            GazouBytes = App.GazouByteRepo.GetAllGazouBytes();
            StatusMessage = "got all file list"; StatusMessage = "got all file list";

            }

            [RelayCommand]
            private void OnFileSave()
            {
            if (gazouName == null) return;

            var gazouByte = new GazouByte
            {
            GazouName = gazouName!,
            GazouBinary = gazouBinary!, //!はNull出ないことを宣言

            GazouExtension = gazouExtension!,
            };

            App.GazouByteRepo.AddNewGazouByte(gazouByte);//←forexample here

            StatusMessage = "file saved";

            }

            [RelayCommand]
            private async Task OnFileSelect() //非同期でTaskとして結果を返す

            {

            try

            {

            var result = await FilePicker.PickAsync();

            if (result == null) return;


            var fileName = result.FileName;

            if (fileName.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) ||

            fileName.EndsWith("png", StringComparison.OrdinalIgnoreCase))

            {

            using (var stream = await result.OpenReadAsync())

            using (var memoryStream = new MemoryStream())

            {

            await stream.CopyToAsync(memoryStream);

            gazouName = fileName;

            gazouBinary = memoryStream.ToArray();

            gazouExtension = result.ContentType;


            var previewStream = new MemoryStream(memoryStream.ToArray());

            UserPreview = ImageSource.FromStream(() => previewStream);

            }

            }

            else

            {

            StatusMessage = "Unsupported file type.";

            }

            }

            catch (Exception ex)

            {

            StatusMessage = $"Error selecting file: {ex.Message}";

            }

            }

            }

       

       

    • Next Episode

      neattanaka.hatenablog.com

*1:In Youtube and .Net . you can watch live streaming video