/*
Mostly code from devdactic (Simon Grimm, best Youtube Chanel for ionic tutorials) and ionic website.
This is code for SQLite database in ionic app.
But there is an issue, when i run it on Android mobile and press (Save Developer) button then nothing happens (Name’s list not shown).
/
/////////////////////////////////////////////////////////////////////////////
/ home.ts file code */
import { Component } from ‘@angular/core’;
import { NavController } from ‘ionic-angular’;
import { SQLite, SQLiteObject } from ‘@ionic-native/sqlite’;
@Component({
selector: ‘page-home’,
templateUrl: ‘home.html’
})
export class HomePage {
database: SQLiteObject;
developers = [];
developer = {};
/* Constructor */
constructor(public navCtrl: NavController, public sqlite: SQLite)
{
this.sqlite.create({
name: 'data.db',
location: 'default'
})
.then((db: SQLiteObject) => {
this.database = db;
db.executeSql('create table developers(name VARCHAR(32))', {})
.then(() => console.log('Executed SQL'))
.catch(e => console.log(e));
});
}
/* Get data from Database */
loadDeveloperData()
{
this.getAllDevelopers().then(data => {
this.developers = data;
});
}
/* Save data to the database, call this function by pressing button */
saveDeveloper()
{
this.addDeveloper(this.developer['name'])
.then(data => {
this.loadDeveloperData();
});
this.developer = {};
}
addDeveloper(name)
{
let data = name;
return this.database.executeSql("INSERT INTO developers (name) Values (?)", data).then( res => {
return res;
});
}
getAllDevelopers()
{
return this.database.executeSql("SELECT * FROM developers", []).then (data => {
let developers = [];
if (data.rows.lenght > 0 )
{
for (var i=0; i < data.rows.length; i++) {
developers.push({name: data.rows.item(i).name})
}
}
return developers;
}, err => {
console.log('Error:', err);
return [];
});
}
}
/////////////////////////////////////////////////////////////////////////////