使用SQLite offline storage API来存储应用的设置

101 阅读2分钟

在前面的一篇文章中,我们已经使用了一种方法U1db来存储我们的应用的设置。这里我们使用另外的一种方法来做同样的事。在这篇文章中,我们使用SQLite的API来存储我们想要存储的东西。事实上这个方法早已经被coreapps里的weather, rss reader及music应用所使用。开发者可以查看launchpad.net/ubuntu-phon…来更详细地了解如何使用这个方法在实际的例子里存储设置的。下面我们来详细的解释如何这么做

\

1)创建一个基本的应用

\

我们使用Qt Create来创建一个“App with Simple UI”的简单template应用。导入如下的库:

\

import QtQuick.LocalStorage 2.0


这样我们就可以使用SQLite API接口来进行数据库的操作了。

\

另外很重要的一点,我们必须使用如下的方法定义一个应用的名称:

\

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.settings"
 ...
}


这样做的目的是为了能够在应用的自己可以访问的目录里创建一个数据库文件。如果不这样做,数据库文件可能会被创建到其他的地方而导致不能被本应用访问。

\

下面我们来创建数据库方法来创建,修改,并存储设置:

\

    function openDB() {
        if(db !== null) return;

        // db = LocalStorage.openDatabaseSync(identifier, version, description, estimated_size, callback(db))
        db = LocalStorage.openDatabaseSync("example-app", "0.1", "Simple example app", 100000);

        try {
            db.transaction(function(tx){
                tx.executeSql('CREATE TABLE IF NOT EXISTS settings(key TEXT UNIQUE, value TEXT)');
                var table  = tx.executeSql("SELECT * FROM settings");
                // Seed the table with default values
                if (table.rows.length == 0) {
                    tx.executeSql('INSERT INTO settings VALUES(?, ?)', ["distro", "Ubuntu"]);
                    tx.executeSql('INSERT INTO settings VALUES(?, ?)', ["foo", "Bar"]);
                    console.log('Settings table added');
                };
            });
        } catch (err) {
            console.log("Error creating table in database: " + err);
        };
    }


    function saveSetting(key, value) {
        openDB();
        db.transaction( function(tx){
            tx.executeSql('INSERT OR REPLACE INTO settings VALUES(?, ?)', [key, value]);
        });
    }

    function getSetting(key) {
        openDB();
        var res = "";
        db.transaction(function(tx) {
            var rs = tx.executeSql('SELECT value FROM settings WHERE key=?;', [key]);
            res = rs.rows.item(0).value;
        });
        return res;
    }

\

2)创建UI来修改,存储设置

\

    Page {
        id: app
        title: i18n.tr("Settings")

        Column {
            anchors.fill: parent
            anchors.margins: units.gu(5)
            spacing: units.gu(2)

            OptionSelector {
                id: distroToggle
                text: i18n.tr("Favorite Distro")
                model: [i18n.tr("Ubuntu"), i18n.tr("Debian")]
            }

            OptionSelector {
                id: fooToggle
                text: i18n.tr("Foo")
                model: [i18n.tr("Bar"), i18n.tr("Baz")]
            }

            Button {
                text: i18n.tr("Save settings")
                onClicked: {
                    var distro = (distroToggle.selectedIndex === 0) ? "Ubuntu" : "Debian";
                    console.log("Saved " + distro);
                    saveSetting("distro", distro);

                    var foo = (fooToggle.selectedIndex === 0) ? "Bar" : "Baz";
                    console.log("Saved " + foo);
                    saveSetting("foo", foo);
                }
            }
        }

        Component.onCompleted: {
            var distro = getSetting('distro');
            distroToggle.selectedIndex = (distro === "Debian") ? 1 : 0;
            var foo = getSetting('foo');
            fooToggle.selectedIndex = (foo === "Baz") ? 1 : 0;
        }
    }


我们来运行该应用:

\

\

\

在手机上的数据库文件:

\

\

\

源码可以在如下地址下载:

\

bzr branch  lp:~liu-xiao-guo/debiantrial/settings\

\

\

\

\

\