我有一个名为Lego_Parts.db3
的文件,这是一个已经填充了数据的SQLite文件。我将其放在Android Xamarin项目的资产文件夹中。我必须设置数据库路径的代码是:
static PieceDB database;
public static PieceDB PieceDatabase
{
get
{
if (database == null)
{
database = new PieceDB(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "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 Catagory { 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>
我有一个名为Lego_Parts.db3的文件,这是一个已经填充了数据的SQLite文件。我将其放在Android Xamarin项目的资产文件夹中。我必须设置数据库路径的代码是:...
您将必须将数据库复制到文件位置。