Cyjan's Blog

I don't know why are you here, but enjoy.


Epstein didn't kill himself | Design | General
Politically Incorrect | Raspberry PI | Technologic
btw I'm using Ubuntu Touch

Qt LocalStorage - Ubuntu Touch clicker app

July 20, 2020 | btw I'm using Ubuntu Touch

In the previous post, we have created a simple clicker app, but it lacks some features, like for example storing the number of clicks, and that's what I've created in this video, and what I'll explain in this post. If you have not followed tutorials, grab this source code.

I've created a new file named qml/scripts/db.js

var db = Database.LocalStorage.openDatabaseSync("Clicker", "1.0", "Clicker SQL Database", 1000000);

That line initializes the database file.

function sql(query, specials, callback, err) {

This one creates sql function, which takes the following parameters:

function set(id, val) {

This function sets things in our keyval table, for example set('doge', 999) will mean that you want to store 999 'doge'

function get(id, callback) {

This function takes an id and run a callback function on it, for example get('doge',function(res) {console.log(res.rows.item(0).val)}) will return 999

sql("CREATE TABLE IF NOT EXISTS keyval(\
id TEXT PRIMARY KEY,\
val TEXT NOT NULL\
)")

This one creates keyval table

I've also made changes to qml/Main.qml

import QtQuick.LocalStorage 2.0 as Database
import "./scripts/db.js" as DB

First-line imported LocalStorage, so we can use it in out script db.js

Then we have changed doge++ into DB.set('doge',++doge); which adds 1 to doge and returns new value to function DB.set, which set it in database with key doge.

Then, later in code, we have added:

Component.onCompleted: {
DB.get('doge', function (res) {
doge = Math.round(Number(res.rows.item(0).val))
})
}

This means that when Component finished loading (onCompleted) we will get the value of 'doge' stored in our DB, and we will run a function that will convert string returned by res.rows.item(0).val to Number, after that, we round it and update doge with that result. So basically, we restore the number of clicks.