Xamarin访问SQLite数据库报错:对象引用未设置为实例
核心问题:接口名称不匹配
你报错代码里调用的是DependencyService.Get<ISQLiteInterface>(),但你定义的接口是ISQLiteConnection,接口名称完全不一致,导致DependencyService.Get返回null,后续调用.GetSQLiteConnection()就会触发“对象引用未设置为对象的实例”错误。
修正步骤
统一接口名称
将报错代码里的ISQLiteInterface改为ISQLiteConnection:_SQLiteConnection = DependencyService.Get<ISQLiteConnection>().GetSQLiteConnection();检查实现类的Dependency特性
确认你的Droid实现类上的[assembly: Dependency(typeof(GetSQLiteConnnection))]特性放在命名空间之外(当前代码是正确的),且GetSQLiteConnnection类确实完整实现了ISQLiteConnection接口。修正SQLiteConnection构造的命名空间
你实现类的方法返回类型是SQLite.Net.SQLiteConnection,但构造实例时写的是SQLiteConnection,可能存在命名空间冲突,建议加上完整命名空间:var connection = new SQLite.Net.SQLiteConnection(platform, path);验证SQLite NuGet包引用
确保共享项目和Droid项目都安装了匹配版本的SQLite相关NuGet包(比如SQLite.Net-PCL),避免因缺少依赖导致实例化失败。确认Xamarin.Forms初始化
在Android项目的MainActivity的OnCreate方法中,确保已完成Xamarin.Forms初始化:protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Xamarin.Forms.Forms.Init(this, savedInstanceState); LoadApplication(new App()); }
额外排查点
- 检查实现类的命名空间
SqliteLoginDemo.Droid.Dependencies是否被正确编译,确保Droid项目能识别到该类。 - 可以先判断服务是否获取成功,避免直接调用方法触发空引用:
var sqliteService = DependencyService.Get<ISQLiteConnection>(); if (sqliteService != null) { _SQLiteConnection = sqliteService.GetSQLiteConnection(); } else { // 处理服务未找到的异常情况 }
内容的提问来源于stack exchange,提问作者user22408554

