【发布时间】:2020-09-08 14:15:39
【问题描述】:
Xamarin 在这里形成新手,我正在尝试建立 SQLite 连接,以便可以与我的应用程序中创建的数据库进行交互。
我在 IDE 中没有得到任何标志,但是当我编译时,我得到一个空引用错误!具体来说,我的_SQLiteConnection var为null,我认为可能与路径设置不正确有关?
我在网上参考了一些指南,虽然有点过时,但他们以与我相同的方式进行设置。
这里有一些代码:
UserDb.cs:
using PluralBuddy.Models;
using SQLite;
using System.Collections.Generic;
using System.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace PluralBuddy.Data
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public class UserDB
{
private SQLiteConnection _SQLiteConnection;
public UserDB()
{
_SQLiteConnection = DependencyService.Get<ISQLiteInterface>().GetConnection();
_SQLiteConnection.CreateTable<User>();
}
ISQLiteInterface.cs:
using SQLite;
namespace PluralBuddy.Models
{
public interface ISQLiteInterface
{
SQLiteConnection GetConnection();
}
}
参考资料:
https://code.tutsplus.com/tutorials/an-introduction-to-xamarinforms-and-sqlite--cms-23020
https://dzone.com/articles/register-and-login-using-sqlite-in-xamarinforms
一如既往,感谢您的帮助!
【问题讨论】:
-
问题应该在这里
DependencyService.Get<ISQLiteInterface>()检查这不会返回null。如果是,请检查您如何处理注册。 -
错误行位于对 DependencyService 的调用上。您在尝试运行之前完成了教程代码吗?
-
是的,据我所知。不过,我可以回去仔细检查。
-
SQLite.NET 不再需要使用 DependencyService。阅读最新的文档以获取示例。如果您想继续使用当前方法,请将 Get() 和 GetConnection() 分成 2 行不同的行,这样您就可以知道是哪一行导致了 null ref。
-
请打开你的dependenceService代码,请确保设置属性是否正确,例如我定义了一个接口是
ISimService,通过SimNumber类实现这个ISimServiceinterface,我需要将属性设置为[assembly: Dependency(typeof(SimNumber))],就像这个截图一样。 imgur.com/a/sfIhDDS
标签: c# sqlite xamarin.forms