• Xamarin.Forms中SQLite.Net的使用


    Xamarin.Forms中SQLite.Net的使用

    最近有朋友问Xamarin中怎么使用Sqlite,所以在这里简单讲讲在安装Sqlite.net后使用时必须解决的问题,Sqlite的具体使用不讲。

     首先,通过nuget包管理器安装Sqlite.Net包。

    然后,需要一个类来创建连接数据库,这个类需要继承自SQLiteConnection。

    public class DataBase : SQLiteConnection
        {
            public DataBase(ISQLitePlatform platform, string dbfilePath):base(platform,dbfilePath)
            {
    
            }
        }
    1. dbfilePath不多说,就是数据库的地址。
    2. platform这里需要说明:
    • iOS中设置 platform = new SQLite.Net.Platform.XamarinIOS.SQLitePlatformIOS();
    • UWP中设置 platform = new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT();
    • Android在这里需要特别说明一下:
      • 在AndroidN即(7.0)以下版本设置 platform = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
      • 在AndroidN以上设置platform = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroidN();

    这里会发现没有这个类,这个类需要单独安装扩展包。如果直接从nuget包管理器下载是无法安装的,因为兼容性的问题。可以从nuget官网去下载,解压后导入dll即可。

    SQLite.Net.Platform.XamarinAndroidN:https://www.nuget.org/packages/SQLite.Net.Platform.XamarinAndroidN

            

    public ISQLitePlatform GetSQLitePlatform()
            {
                if(Build.VERSION.SdkInt >= Build.VERSION_CODES.N)
                {
                    return new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroidN();
                }
                else
                {
                    return new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
                }
            }

    到这里,ios、UWP中数据库可以正常使用了,但是Android还会报错(Unhandled Exception: System.DllNotFoundException: libsqlite3_xamarin),这是为什么呢?

    官方文档这样说的:

    https://developer.xamarin.com/releases/android/xamarin.android_6/xamarin.android_6.0/

    Due to a change by Google, Android N will now only permit linking to NDK-provided native librarieslibsqlite.so is not an NDK-provided native library. Consequently, existing apps using e.g. Mono.Data.Sqlite.dll will crash when running on Android N. This may include other SQLite-using assemblies, not distributed with Xamarin.Android.

    在andorid7.0后,不允许应用调用系统的sqlite,所以需要应用自己引入。

    这时我们需要在Android项目中安装Mono.Data.Sqlite.Portable(nuget中直接下载即可),这样Android中也可以使用Sqlite了。

  • 相关阅读:
    全选、全不选、反选
    IE Tester 怎样使用firebug 调试工具?
    策略模式
    模板方法模式
    迭代器模式——android中使用
    android 实现圆形波纹动画
    android 窗口的使用
    AlertDialog 基本使用
    国外android 网站
    ViewDragHelper 任意拖动
  • 原文地址:https://www.cnblogs.com/devin_zhou/p/9243087.html
Copyright © 2020-2023  润新知