【发布时间】:2019-02-04 14:35:36
【问题描述】:
我正在尝试创建一个 SQLite 数据库,但出现异常。该错误没有说明异常发生的原因。它只是说一个空引用异常。 异常发生在这一行
var connection = `DependencyService.Get<ISQLiteDB>().GetConnection();`
在构造函数中。
这是我的 .cs 文件
using App4.Persistence;
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace App4
{
public class Contact
{
[PrimaryKey,AutoIncrement]
public int Id { get; set; }
[MaxLength (255)]
public string Name { get; set; }
}
public partial class MainPage : ContentPage
{
public string ConnectionPath { get; set; }
public MainPage()
{
InitializeComponent();
var connection = DependencyService.Get<ISQLiteDB>().GetConnection();
}
protected async override void OnAppearing()
{
var connection = new SQLiteAsyncConnection(ConnectionPath);
await connection.CreateTableAsync<Contact>();
var contacts = await connection.Table<Contact>().ToListAsync();
listViewContacts.ItemsSource = contacts;
base.OnAppearing();
}
private void buttonAdd_Clicked(object sender, EventArgs e)
{
}
private void buttonDelete_Clicked(object sender, EventArgs e)
{
}
private void buttonUpdate_Clicked(object sender, EventArgs e)
{
}
}
}
这是我用来通过在 iOS 和 Android 中以不同方式实现它来获取数据库路径的路径
>
> using SQLite;
> using System;
> using System.Collections.Generic;
> using System.Text;
>
> namespace App4.Persistence
> {
> public interface ISQLiteDB
> {
> SQLiteAsyncConnection GetConnection();
>
> }
> }
这是 iOS 和 Android 中的实现。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using App4.Persistence;
using SQLite;
namespace App4.Droid.Persistence
{
public class SQLiteDB : ISQLiteDB
{
public SQLiteAsyncConnection GetConnection()
{
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
var DatabasePath = Path.Combine(documentsPath,"MySQLite.db3");
return new SQLiteAsyncConnection(DatabasePath);
}
}
}
虽然 iOS 和 Android 的实现是相同的(并且在这种情况下不需要接口),但我将为需要不同实现以获取数据库路径的窗口创建项目。
感谢任何帮助。
谢谢。
【问题讨论】:
标签: sqlite xamarin.forms nullreferenceexception