保存数据对于一些应用来说非常重要。比如在游戏闯关的时候,我们需要保存当前的关及一些应用的设置等。
1)创建数据库及文档
我们用Qt SDK来创建一个简单的应用。同时加入如下的库:
import U1db 1.0 as U1db
为了能够在手机上创建我们所需要的数据库文件,我们必须定义好自己的应用名称“com.ubuntu.developer.liu-xiao-guo.u1db”:
MainView {
// objectName for functional testing purposes (autopilot-qt5)
objectName: "mainView"
// Note! applicationName needs to match the "name" field of the click manifest
applicationName: "com.ubuntu.developer.liu-xiao-guo.u1db"
anchorToKeyboard: true
首先我们来创建一个数据库:
U1db.Database {
id: aDatabase
path: "aDatabase"
}
创建一个数据库非常容易,它需要一个id及一个path。这个path用来标示数据库文件被创建的路经。一个数据库就是一个model。它可以被其他的元素所引用。比如说listview。
另外我们也需要创建一个document:
U1db.Document {
id: aDocument
database: aDatabase
docId: 'helloworld'
create: true
defaults: { "hello": "Hello World!" }
}
这个document除了一个id及一个docId以外并没有什么特别的地方。这俩个定义有些时候并不是必须的,虽然在某种情况下使得引用变得更加容易。document可以在runtime时动态地创建。在上面的例子里,我们设置create为true。在没有contents定义的情况下,defaults所定义的值将被设置为默认的值。
如果我们有如下的定义:
U1db.Document {
id: aDocument
database: aDatabase
docId: 'helloworld'
create: true
defaults: { "hello": "Hello World!" }
contents: {"hello" : "nin hao!" }
}
2)显示及修改数据库
为了显示数据库中的数据,我们使用一个listview。
ListView {
width: units.gu(45)
height: units.gu(30)
/*
Here is the reference to the Database model mentioned earlier.
*/
model: aDatabase
/* A delegate will be created for each Document retrieved from the Database */
delegate: Text {
text: {
/*!
The object called 'contents' contains a string as demonstrated here. In this example 'hello' is our search string.
text: contents.hello
*/
text: contents.hello
}
}
}
为了显示修改我们的数据库数据,我们加入如下的代码:
TextField {
id: value
placeholderText: "please input a new value"
text:"good"
}
Button {
id: modify
text: "Modify"
height: units.gu(5)
width: units.gu(25)
onClicked: {
aDocument.contents = { "hello": value.text }
}
}
这里我们通过aDocument来直接对"hello"中的数据进行修改。运行效果如下:
在手机上运行后,我们可以查看在手机上生成的文件及路经:
整个代码可以在如下地址找到:
bzr branch lp:~liu-xiao-guo/debiantrial/u1db