我有一个名为Lego_Parts.db3
的文件,这是一个已经填充了数据的SQLite文件。我将其放在Android Xamarin项目的资产文件夹中。我必须设置数据库路径的代码是:
static PieceDB database;
public static PieceDB PieceDatabase
{
get
{
if (database == null)
{
database = new PieceDB(Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),"Lego_Parts.db3"));
}
return database;
}
}
当我尝试显示数据库中的数据(在DatabaseTest.xaml中)时,没有数据显示
以下是任何适用的代码:
Piece.cs
using SQLite;
namespace TestApp1
{
public class Piece
{
public int PartNum { get; set; }
public string PartName { get; set; }
public string Category { get; set; }
public string Url { get; set; }
}
}
PieceDB.cs
using SQLite;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace TestApp1
{
public class PieceDB
{
readonly SQLiteAsyncConnection _database;
public PieceDB(string dbPath)
{
_database = new SQLiteAsyncConnection(dbPath);
_database.CreatetableAsync<Piece>().Wait();
}
public Task<List<Piece>> GetallPieces()
{
return _database.Table<Piece>().ToListAsync();
}
public Task<Piece> GetPiece(int partNum)
{
return _database.Table<Piece>().Where(i => i.PartNum == partNum).FirstOrDefaultAsync();
}
public Task<int> SavePieceAsync(Piece temp)
{
return _database.InsertAsync(temp);
}
}
}
DatabaseTest.xaml.cs
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace TestApp1
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class DatabaseTest : ContentPage
{
protected override async void OnAppearing()
{
base.OnAppearing();
listView.ItemsSource = await App.PieceDatabase.GetallPieces();
}
public DatabaseTest()
{
InitializeComponent();
}
async void Handle_ItemTapped(object sender,ItemTappedEventArgs e)
{
if (e.Item == null)
return;
await DisplayAlert("Item Tapped","An item was tapped.","OK");
//Deselect Item
((ListView)sender).SelectedItem = null;
}
}
}
DatabaseTest.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="TestApp1.DatabaseTest">
<StackLayout Margin="20,35,20,20">
<ListView x:Name="listView">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding PartNum}"
Detail="{Binding Url}"
/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>