xamarin 为什么此SQLite连接始终为空?

vjhs03f7  于 2022-12-07  发布在  SQLite
关注(0)|答案(2)|浏览(105)

我有一段代码,我甚至不知道如何初始化它。我尝试了几个不同的版本,但所有的都出现了一个警告说
警告CS0649字段“NoteService.db”从未被赋值,其默认值始终为null
我尝试创建此表的部分如下所示:

static SQLiteAsyncConnection db;
    static async Task Init()
    {

        if (db != null)
            return;
        {
            var databasePath = Path.Combine(FileSystem.AppDataDirectory, "MyData.db");

            db = new SQLiteAsyncConnection(databasePath);

            await db.CreateTableAsync<Note>();
        }
    }

这是完整的代码
MyNoteViewModel.cs:

namespace MyApp.ViewModels {
public class MyNoteViewModel : ViewModelBase
{

    public ObservableRangeCollection<Note> Note { get;}
    public AsyncCommand RefreshCommand { get; }

    public AsyncCommand AddCommand { get; }

    public AsyncCommand<Note> RemoveCommand { get; }
    public new bool IsBusy { get; private set; }

    public MyNoteViewModel()
    {

        Note = new ObservableRangeCollection<Note>();

        RefreshCommand = new AsyncCommand(Refresh);
        AddCommand = new AsyncCommand(Add);
        RemoveCommand = new AsyncCommand<Note>(Remove);
    }

    async Task Add()
    {
        var name = await App.Current.MainPage.DisplayPromptAsync("Notes", "Enter your notes here");
        await NoteService.AddNote(name);
        await Refresh();
    }

    async Task Remove(Note note)
    {
        await NoteService.RemoveNote(note.Id);
        await Refresh();
    }

    
    async Task Refresh()
    {
        IsBusy = true;
        await Task.Delay(2000);
        Note.Clear();
        var notes = NoteService.GetNote();
        Note.AddRange((IEnumerable<Note>)notes);
        IsBusy = false;
        return;
    }

NotePage.xaml:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:model="clr-namespace:MyApp.Models"
         xmlns:mvvm="clr-namespace:MvvmHelpers;assembly=MvvmHelpers"
         xmlns:viewmodels="clr-namespace:MyApp.ViewModels"
         xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
         x:Class="MyApp.MyNotePage"
         x:Name="MyNotePage"
         x:DataType="viewmodels:MyNoteViewModel"
         BackgroundColor="White">
<ContentPage.BindingContext>
    <viewmodels:MyNoteViewModel/>
</ContentPage.BindingContext>

<ContentPage.Resources>
    <ResourceDictionary>
        <xct:ItemSelectedEventArgsConverter x:Key="ItemSelectedEventArgsConverter"/>
    </ResourceDictionary>
</ContentPage.Resources>

<ContentPage.ToolbarItems>
    <ToolbarItem Text="Add" Command="{Binding AddCommand}"/>
</ContentPage.ToolbarItems>

<ListView
    BackgroundColor="Transparent"
    CachingStrategy="RecycleElement"
    HasUnevenRows="True"
    IsPullToRefreshEnabled="True"
    IsRefreshing="{Binding IsBusy, Mode=OneWay}"
    ItemsSource="{Binding Note}"
    RefreshCommand="{Binding RefreshCommand}"
    RefreshControlColor="DarkViolet"
    SelectionMode="None"
    SeparatorVisibility="None">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="model:Note">
            <ViewCell>
                <ViewCell.ContextActions>
                    <MenuItem
                        Command="{Binding Source={x:Reference MyNotePage}, Path=BindingContext.RemoveCommand}"
                        CommandParameter="{Binding .}"
                        IsDestructive="True"
                        Text="Delete"/>
                </ViewCell.ContextActions>
                <Grid Padding="10">
                    <Frame CornerRadius="20" HasShadow="True">
                        <StackLayout Orientation="Horizontal">
                            <StackLayout VerticalOptions="Center">
                                <Label
                                    FontSize="Large"
                                    Text="{Binding Name}"
                                    VerticalOptions="Center"/>
                                <Label
                                    FontSize="Small"
                                    Text="{Binding Id}"
                                    VerticalOptions="Center"/>
                            </StackLayout>
                        </StackLayout>
                    </Frame>
                </Grid>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

NotePage.xaml.cs:

namespace MyApp
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MyNotePage
    {
        public MyNotePage()
        {
            InitializeComponent();
        }
    }
}

NoteService.cs:

namespace MyApp.Services
{
    public static class NoteService
    {

        static SQLiteAsyncConnection db;
        static async Task Init()
        {

            if (db != null)
                return;
            {
                var databasePath = Path.Combine(FileSystem.AppDataDirectory, "MyData.db");

                db = new SQLiteAsyncConnection(databasePath);

                await db.CreateTableAsync<Note>();
            }
        }

        public static async Task AddNote(string name)
        {
            await Init();
            var note = new Note()
            {
                Name = name,
            };

            var id = await db.InsertAsync(note);
            
        }
        public static async Task RemoveNote(int id)
        {
            await Init();
            await db.DeleteAsync<Note>(id);

        }
        public static async Task<IEnumerable<Note>> GetNote()
        {
            await Init();

            var note = await db.Table<Note>().ToListAsync();
            return note;

        }

    }
}
a8jjtwal

a8jjtwal1#

GetNoteasync,但在调用它时没有使用await。这意味着notesTask。然后,当您尝试转换它时,转换失败并返回null,这将导致NullRef异常

var notes = NoteService.GetNote();
Note.AddRange((IEnumerable<Note>)notes);

相反,请执行以下操作

var notes = await NoteService.GetNote();
Note.AddRange(notes);
8cdiaqws

8cdiaqws2#

var db = new SQLiteAsyncConnection(databasePath);

您正在建立方法范围内的新字段,这是编译器允许的,但不是您想要的。请移除var保留字以指涉类别层级字段。

相关问题