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." [![There is no data in the browser.][1]][1]
Steps to Reproduce
Specific steps to reproduce the issue: Start debugging in Visual Studio 2022 on a Windows machine. Click on "Select File" to open the file picker and choose an image file (jpg/png). Verify that the image preview is displayed under "Select File." Click the "Save File" button and confirm that "file saved" is displayed. Check the database using "DB Browser for SQLite"; the table is created, but no data is saved. enter image description here
using WorkReview.Models;
using System.Collections.Generic;
using Microsoft.Maui.Controls;
using WorkReview.ViewModels;
using System.Runtime.CompilerServices;
namespace WorkReview.Views
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
BindingContext = new MainViewModel();
}
public void OnGetAllGazouClicked(object sender, EventArgs args)
{
List<GazouByte> gazouByte = App.GazouByteRepo.GetAllGazouBytes();
statusMessage.Text = "got all file list";
}
public void OnFileSaveClicked(object sender, EventArgs args)
{
(BindingContext as MainViewModel).SaveGazouToDataBase(); //BindingVontextのインスタンスをもちいて.Save~メソッドを実行している
statusMessage.Text = "file saved";
}
public async void OnFileSelectClicked(object sender, EventArgs args)
{
try
{
var result = await FilePicker.PickAsync();
var fileExtension = result.ContentType;
var fileName = result.FileName;
if (result != null)
{
if (result.FileName.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) ||
result.FileName.EndsWith("png", StringComparison.OrdinalIgnoreCase))
{
using (var stream = await result.OpenReadAsync())
{
using (var memoryStream = new MemoryStream())///using(var)はUsingステートメント,{}内の処理が終わったときにリソースが開放される
{
await stream.CopyToAsync(memoryStream); //memoryStreamに保存されたデータをViewModelの該当箇所へ送る / send data to viewmodel
(BindingContext as MainViewModel).gazouExtension = fileExtension;
(BindingContext as MainViewModel).gazouName = fileName;
(BindingContext as MainViewModel).gazouBinary = memoryStream.ToArray();
var previewStream = new MemoryStream(memoryStream.ToArray());
userPreview.Source = ImageSource.FromStream(() => previewStream);
}
}
}
else
{
statusMessage.Text = "Unsupported file type.";
}
}
}
catch (Exception ex)
{
statusMessage.Text = $"Error selecting file: {ex.Message}";
}
}
}
}
Repositry here
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WorkReview.Models;
namespace WorkReview.Models
{
public class GazouByteRepositry
{
string _gazoudbPath;
public string GazouStatusMessage { get; set; }
private SQLiteConnection gazouconn;
public GazouByteRepositry(string gazoudbPath)
{
_gazoudbPath = gazoudbPath;
}
private void Init() //dbに接続後テーブル作成 create table when connect db.3
{
if (gazouconn is not null)
return;
gazouconn = new SQLiteConnection(_gazoudbPath);
gazouconn.CreateTable<GazouByte>();
}
public void AddNewGazouByte(string gazouName, byte[] gazouBinary, string gazouExtension)//画��データをDBへ挿入 add image data to db.3
{
ArgumentNullException.ThrowIfNull(gazouName, nameof(gazouExtension));
ArgumentNullException.ThrowIfNull(gazouBinary, nameof(gazouBinary));
ArgumentNullException.ThrowIfNull(gazouName, nameof(gazouName));
int gazouResult = 0;
try
{
Init();
gazouResult = gazouconn.Insert(new GazouByte { GazouName = gazouName, GazouBinary = gazouBinary, GazouExtension = gazouExtension });
Console.WriteLine($"Insert result: {gazouResult}");
GazouStatusMessage = string.Format("{0} record(s) added (GazouName: {1})", gazouResult, gazouName);
}
catch (Exception ex)
{
GazouStatusMessage = string.Format("Failed to add {0}. Error: {1}", gazouName, ex.Message);
}
}
public List<GazouByte> GetAllGazouBytes()//テーブルを取得 get table then create list for controll-view .MainPage
{
try
{
Init();
return gazouconn.Table<GazouByte>().ToList();
}
catch (Exception ex)
{
GazouStatusMessage = string.Format("Failed to retrieve data .{0}", ex.Message);
}
return new List<GazouByte>();
}
}
}
Table is here
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommunityToolkit;
namespace WorkReview.Models;
[Table("gazouByte")]
public class GazouByte
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string GazouName { get; set; }
public byte[] GazouBinary { get; set; } //画像のバイナリ用 Binary fo image to db.3
public string GazouExtension { get; set; }
}
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
Additional Information
The complete code can be found at the following URL: https://github.com/rasukuosu/WorkReview.git