android使用的数据,在 Android 应用中使用数据 - Xamarin | Microsoft Docs

在应用中使用数据Using Data in an App

02/08/2018

本文内容

DataAccess_Adv示例显示允许用户输入和 CRUD (创建、读取、更新和删除)数据库功能的工作应用程序。The DataAccess_Adv sample shows a working application that allows user-input and CRUD (Create, Read, Update and Delete) database functionality. 该应用程序包含两个屏幕:一个列表和一个数据输入窗体。The application consists of two screens: a list and a data entry form. 所有数据访问代码在 iOS 和 Android 中可重复使用,而无需修改。All the data access code is re-usable in iOS and Android without modification.

添加一些数据后,应用程序屏幕上的应用程序屏幕将如下所示:After adding some data the application screens look like this on Android:

941f04cad04be1a4691d5863598ddf86.png941f04cad04be1a4691d5863598ddf86.png

90bc7dba5f7a8f6ad3c64f3e47383b34.png90bc7dba5f7a8f6ad3c64f3e47383b34.png

Android 项目显示在下面 – 此部分中所示代码包含在Orm目录中:The Android Project is shown below – the code shown in this section is contained within the Orm directory:

c56fbeb31cc6156768b27bc4b671aff2.pngc56fbeb31cc6156768b27bc4b671aff2.png

Android 中的活动的本机 UI 代码超出了本文档的范围。The native UI code for the Activities in Android is out of scope for this document. Refer to the Android ListViews and Adapters guide for more information on the UI controls.

读取Read

示例中有两个读取操作:There are a couple of read operations in the sample:

阅读列表Reading the list

读取单个记录Reading individual records

StockDatabase 类中的两个方法是:The two methods in the StockDatabase class are:

public IEnumerable GetStocks ()

{

lock (locker) {

return (from i in Table () select i).ToList ();

}

}

public Stock GetStock (int id)

{

lock (locker) {

return Table().FirstOrDefault(x => x.Id == id);

}

}

Android 以 ListView 的形式呈现数据。Android renders the data as a ListView.

创建和更新Create and Update

为了简化应用程序代码,提供了一个 save 方法,该方法根据 PrimaryKey 是否已设置,执行插入或更新。To simplify the application code, a single save method is provided that does an Insert or Update depending on whether the PrimaryKey has been set. 由于 Id 属性使用 [PrimaryKey] 属性进行标记,因此不应在代码中对其进行设置。Because the Id property is marked with a [PrimaryKey] attribute you should not set it in your code. 此方法将检测是否之前已保存值(通过检查主键属性),并相应地插入或更新对象:This method will detect whether the value has been previous saved (by checking the primary key property) and either insert or update the object accordingly:

public int SaveStock (Stock item)

{

lock (locker) {

if (item.Id != 0) {

Update (item);

return item.Id;

} else {

return Insert (item);

}

}

}

实际的应用程序通常需要进行一些验证(例如,必填字段、最小长度或其他业务规则)。Real world applications will usually require some validation (such as required fields, minimum lengths or other business rules). 良好的跨平台应用程序在共享代码中实现尽可能多的验证逻辑,将验证错误传递给 UI,以根据平台的功能显示。Good cross-platform applications implement as much of the validation logical as possible in shared code, passing validation errors back up to the UI for display according to the platform's capabilities.

删除Delete

与 Insert 和 Update 方法不同,Delete 方法只接受主键值而不接受完整的 Stock 对象。Unlike the Insert and Update methods, the Delete method can accept just the primary key value rather than a complete Stock object. 在此示例中,将一个 Stock 对象传递到方法中,但仅将 Id 属性传递到 Delete 方法。In this example a Stock object is passed into the method but only the Id property is passed on to the Delete method.

public int DeleteStock(Stock stock)

{

lock (locker) {

return Delete (stock.Id);

}

}

使用预先填充的 SQLite 数据库文件Using a pre-populated SQLite database file

某些应用程序附带已填充数据的数据库。Some applications are shipped with a database already populated with data. 可以在移动应用程序中轻松完成此项工作,方法是:将现有 SQLite 数据库文件与应用程序一起传送,并将其复制到可写目录,然后再访问该文件。You can easily accomplish this in your mobile application by shipping an existing SQLite database file with your app and copying it to a writable directory before accessing it. 由于 SQLite 是在许多平台上使用的标准文件格式,因此可以使用多种工具来创建 SQLite 数据库文件:Because SQLite is a standard file format that is used on many platforms, there are a number of tools available to create an SQLite database file:

SQLite 管理器 Firefox 扩展– 在 Mac 和 Windows 上工作,并生成与 IOS 和 Android 兼容的文件。SQLite Manager Firefox Extension – Works on Mac and Windows and produces files that are compatible with iOS and Android.

创建与应用程序一起分发的数据库文件时,请注意表和列的命名,以确保它们与代码所需的名称匹配,尤其是在使用 SQLite.NET 时,这会希望名称与C#类和属性匹配(或关联的自定义特性)。When creating a database file for distribution with your app, take care with the naming of tables and columns to ensure they match what your code expects, especially if you're using SQLite.NET which will expect the names to match your C# classes and properties (or the associated custom attributes).

若要确保某些代码在 Android 应用中的其他任何位置之前运行,可以将其放在第一个要加载的活动中,也可以创建在任何活动之前加载的 Application 子类。To ensure that some code runs before anything else in your Android app, you can place it in the first activity to load or you can create an Application subclass that is loaded before any activities. 下面的代码演示了一个 Application 子类,该子类将现有数据库文件数据复制到 /Resources/Raw/ 目录中。The code below shows an Application subclass that copies an existing database file data.sqlite out of the /Resources/Raw/ directory.

[Application]

public class YourAndroidApp : Application {

public override void OnCreate ()

{

base.OnCreate ();

var docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

Console.WriteLine ("Data path:" + Database.DatabaseFilePath);

var dbFile = Path.Combine(docFolder, "data.sqlite"); // FILE NAME TO USE WHEN COPIED

if (!System.IO.File.Exists(dbFile)) {

var s = Resources.OpenRawResource(Resource.Raw.data); // DATA FILE RESOURCE ID

FileStream writeStream = new FileStream(dbFile, FileMode.OpenOrCreate, FileAccess.Write);

ReadWriteStream(s, writeStream);

}

}

// readStream is the stream you need to read

// writeStream is the stream you want to write to

private void ReadWriteStream(Stream readStream, Stream writeStream)

{

int Length = 256;

Byte[] buffer = new Byte[Length];

int bytesRead = readStream.Read(buffer, 0, Length);

// write the required bytes

while (bytesRead > 0)

{

writeStream.Write(buffer, 0, bytesRead);

bytesRead = readStream.Read(buffer, 0, Length);

}

readStream.Close();

writeStream.Close();

}

}

相关链接Related Links

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值