在nativescript应用程序中显示sqlite db数据时出现问题

时间:2016-11-16 15:45:49

标签: javascript sqlite nativescript

我的应用程序有一个记分板页面,该页面应该从sqlite数据库中获取数据并在ListView中的NavigatingTo页面上显示,但它没有按预期执行。

显示结果的xml页面:

<Page xmlns="http://schemas.nativescript.org/tns.xsd" loaded="pageLoaded" navigatingTo="onNavigatingTo">

<ActionBar title="Scoreboard">
  <NavigationButton text="Back" android.systemIcon="ic_menu_back" tap="homeTap"/>
</ActionBar>

<StackLayout orientation="vertical">        
    <Label text="Your Performance Sheet"></Label>
    <ListView items= "{{results}}" > 
        <ListView.itemTemplate>
            <Label text="{{testname}}"/>
            <Label text="{{score}}"/>
            <Label text="{{percent}}"/>
        </ListView.itemTemplate>
    </ListView>
</StackLayout>

</Page>         

记分牌 - 视图模型:

var Observable = require("data/observable").Observable;
var ObservableArray = require("data/observable-array").ObservableArray;
var Sqlite = require("nativescript-sqlite");

function scoreViewModel (database) {

var viewModel = new Observable();

viewModel.results = new ObservableArray([]);

viewModel.select = function () {
    this.results = new ObservableArray([]);
    database.all("SELECT * FROM scores").then(rows => {

    for (var row in rows) {         
        this.results.push(rows[row]); 
    }
    }, error => {
        console.log("SELECT ERROR", error);
    })
}   
viewModel.select();

return viewModel;       
}

exports.scoreViewModel = scoreViewModel; 

我正在从得分表中选择所有数据并推送到已绑定到视图的viewModel.results数组。

记分板.js:

var observable = require("data/observable");
var scoreViewModel = require("./scoreboard-view-model").scoreViewModel;
var page;
var Sqlite = require("nativescript-sqlite");

exports.onNavigatingTo = function (args) {
page = args.object;


(new Sqlite("scoreboard.db")).then(db => {
    db.execSQL("CREATE TABLE IF NOT EXISTS scores (id INTEGER PRIMARY KEY AUTOINCREMENT, testname TEXT, score TEXT, percent TEXT)")
    .then(id => {
        page.bindingContext = scoreViewModel(db);           
    }, error => {
        console.log(error)
    });
}, error => {
    console.log(error);
});
}

有人请帮我把数据显示在列表视图中。

1 个答案:

答案 0 :(得分:1)

我通过编辑scoreboard-view-model.js文件来完成它,正是在viewModel.Select函数中:

viewModel.select = function () {
    //the line below was changed to this...
    //testname, score, and percent are column names in the scores table
    database.all("SELECT testname, score, percent FROM scores").then(rows => {

    for (var row in rows) {
        //the line below was changed too...     
        viewModel.results.push({testname: rows[row][0], score: rows[row][1], percent: rows[row][2]});
    }, error => {
        console.log("SELECT ERROR", error);
    })
}   

完成。它现在按预期工作。感谢TJ Vantoll试图提供帮助。真的很感激。