无法从Xamarin.Android中的Sqlite获取数据

时间:2015-07-01 05:27:59

标签: c# android sqlite xamarin.android

我正在使用本教程在我的应用中显示sqlite数据。 Use a local database in Xamarin 但它对我不起作用。帮我解决代码中的错误。 Visual Studio上显示的错误是"发生未处理的异常",并且应用程序无法在我的手机上打开。我没有使用任何模拟器。 感谢

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

using System.Data;
using System.IO;
using SQLite;

namespace DicApp
{
public class Album
{
    [PrimaryKey, AutoIncrement]
    public int AlbumId { get; set; }
    public string Title { get; set; }
    public int ArtistId { get; set; }
}

[Activity(Label = "DicApp", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        string dbName = "db.sqlite";
        string dbPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(), dbName);
        // Check if your DB has already been extracted.
        if (!File.Exists(dbPath))
        {
            using (BinaryReader br = new BinaryReader(Assets.Open(dbName)))
            {
                using (BinaryWriter bw = new BinaryWriter(new FileStream(dbPath, FileMode.Create)))
                {
                    byte[] buffer = new byte[2048];
                    int len = 0;
                    while ((len = br.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        bw.Write(buffer, 0, len);
                    }
                }
            }
        }

        using (var conn = new SQLite.SQLiteConnection(dbPath))
        {
            var cmd = new SQLite.SQLiteCommand (conn);
cmd.CommandText = "select * from Album";
var r = cmd.ExecuteQuery<Album> ();

Console.Write (r);
        }
    }

}
}

0 个答案:

没有答案