I am running Ionic 2 RC4 and when I run ionic run android the app works, but device ready is firing after 15-18 seconds. I tried to run on device ionic run android --prod, but it shows in chrome inspector that sqlite plugin is not installed which is not true. If I go to another page and come back it shows my data from SQLite.
constructor is called
main.js:1 Native: tried accessing the SQLite plugin but it's not installed.
x # main.js:1
main.js:1 Install the SQLite plugin: 'ionic plugin add cordova-sqlite-storage'
x # main.js:1
cordova.js:1223 deviceready has not fired after 5 seconds.
cordova.js:1216 Channel not fired: onFileSystemPathsReady
main.js:4 Native: deviceready did not fire within 2000ms. This can happen when plugins are in an inconsistent state. Try removing plugins from plugins/ and reinstalling them.
(anonymous) # main.js:4
main.js:4 DEVICE READY FIRED AFTER 2684 ms
error getting scheduled matches TypeError: Cannot read property 'executeSql' of undefined
at _ (main.js:1)
at main.js:1
at main.js:1
at new t (polyfills.js:3)
at e (main.js:1)
at s (main.js:1)
at t.<anonymous> (main.js:1)
at t.value [as executeSql] (main.js:1)
at t.getScheduledMatches (main.js:9)
at t.getMatchInfo (main.js:23)
I tried to place device ready in several different locations and I also logged in many places. The last console log that is called is called constructor
constructor(public timeSince: TimeSinceService,
public platform: Platform) {
console.log("constructor is called"); //called
if(!this.isOpen){
this.db = new SQLite();
this.db.openDatabase({name: "aces.db", location: "default"}).then(() => {
console.log("open Database"); // not called
this.db.executeSql('PRAGMA user_version = 0', []).then(()=>console.log("yesss")) // not called
this.db.executeSql('PRAGMA user_version', []).then(data => {
if(data.rows.item(0).user_version !== current_version){
console.log("versions do not match");
}
})
this.db.executeSql('PRAGMA foreign_keys = ON', []).then(()=>{
let query_matches = 'CREATE TABLE IF NOT EXISTS matches '+
'(id INTEGER PRIMARY KEY AUTOINCREMENT,'+
...';
let query_comments = 'CREATE TABLE IF NOT EXISTS comments '+
'(id INTEGER PRIMARY KEY AUTOINCREMENT, '+
...';
let query_points = 'CREATE TABLE IF NOT EXISTS undo'+
'(point_id INTEGER PRIMARY KEY AUTOINCREMENT,'+
...';
let query_organizations = 'CREATE TABLE IF NOT EXISTS organizations '...
let query_users = 'CREATE TABLE IF NOT EXISTS users '+
'(id INTEGER PRIMARY KEY AUTOINCREMENT,'+
...';
Promise.all([
this.db.executeSql(query_matches, {}).then(() => {
console.log("table created");
}, (err) => console.error('Unable to execute sql for matches: ', err)),
this.db.executeSql(query_comments, {}).then(() => {
console.log("comment table created");
}, (err) => console.error('Unable to execute sql for create comment table: ', err)),
this.db.executeSql(query_organizations, {}).then(() => {
console.log("table organizations created");
}, (err) => console.error('Unable to execute sql: ', err)),
this.db.executeSql(query_points, {}).then(() => {
console.log("undo table created");
}, (err) => console.error('Unable to execute sql for undo table: ', err)),
this.db.executeSql(query_users, {}).then(() => {
console.log("table users created");
}, (err) => console.error('Unable to execute sql: ', err))
]).then(()=> {
console.log("called promise all");
this.isOpen = true
})
})
}, (error) => console.log("ERROR couldn't open database from sqlite service: ", error));
}
}
Answering my own question in case somebody runs into the same problem.
I had to call rootPage inside DeviceReady inside my app.component.ts. I hope it helps to somebody.
Related
I do have a really minimalistic react-native app which should read data from a pre-populated database.
var SQLite = require('react-native-sqlite-storage');
SQLite.DEBUG(true);
SQLite.enablePromise(false);
const db = SQLite.openDatabase({
name: 'config.db',
location: 'default'
}, () => {
console.log('db connection success')
}, () => {
console.log('db connection error')
});
The console says:
db connection success
if I run a qry, I do always get an error that the table could not be found:
db.transaction((tx) => {
console.log('TX');
tx.executeSql('SELECT * FROM test',
[],
(tx, results) => {
console.log(results)
var temp = [];
for (let i = 0; i < results.rows.length; ++i)
temp.push(results.rows.item(i));
console.log(temp);
});
});
Error:
SQLite.backgroundExecuteSqlBatch({"dbargs":{"dbname":"config.db"},"executes":[{"qid":1111,"sql":"BEGIN","params":[]},{"qid":1111,"sql":"SELECT * FROM tbl_user","params":[]}]})
Error handler not provided: {"code": 0, "message": "no such table: tbl_user(code 1 SQLITE_ERROR): , while compiling: SELECT * FROM tbl_user"}
warning - exception while invoking a callback:{"code":0,"line":116571,"column":27,"sourceURL":"http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false"}
SQLite.backgroundExecuteSqlBatch({"dbargs":{"dbname":"config.db"},"executes":[{"qid":1111,"sql":"ROLLBACK","params":[]}]})
if I open the database from my Project it shows the table and the data. I put the databe into
\android\app\src\main\assets\www and \android\app\src\main\assets\
What am I doing wrong?
Im about to build a Ionic Inventory Management app with Barcode Scanner and SQLite with the help of this tutorial: https://www.techiediaries.com/ionic-cordova-sqlite-barcode-scanner-product-inventory-manager/
When I add this code:
constructor(public sqlite :SQLite) {
console.log('Hello DataServiceProvider Provider')
this.sqlite.create({name: "data.db", location:
"default"}).then((db : SQLiteObject) => {
this.database = db;
}, (error) => {
console.log("ERROR: ", error);
});
...to data-service.service.ts I got this error:
core.js:19866 ERROR Error: Uncaught (in promise): TypeError: Cannot
read property 'then' of undefined TypeError: Cannot read property
'then' of undefined
at new DataServiceService (data-service.service.ts:64)
at _createClass (core.js:26976)
at createProviderInstance (core.js:26941)
at resolveNgModuleDep (core.js:26888)
at NgModuleRef.get (core.js:27996)
at resolveNgModuleDep (core.js:26908)
at NgModuleRef_.get (core.js:27996)
at resolveDep (core.js:28518)
at createClass (core.js:28366)
at createDirectiveInstance (core.js:28186)
at resolvePromise (zone.js:831)
at resolvePromise (zone.js:788)
at zone.js:892
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask
(zone.js:423)
at Object.onInvokeTask (core.js:21826)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask
(zone.js:422)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
at drainMicroTaskQueue (zone.js:601)
This is the whole data-service.service.ts code:
import { Injectable } from '#angular/core';
import { SQLite, SQLiteObject } from '#ionic-native/sqlite/ngx';
#Injectable({
providedIn: 'root'
})
export class DataServiceService {
public database: SQLiteObject;
productTable : string = `CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY,
sku TEXT,
barcode TEXT,
title TEXT NOT NULL,
description TEXT,
quantity REAL,
unit VARCHAR,
unitPrice REAL,
minQuantity INTEGER,
familly_id INTEGER,
location_id INTEGER,
FOREIGN KEY(familly_id) REFERENCES famillies(id),
FOREIGN KEY(location_id) REFERENCES locations(id)
);`;
familyTable : string = `CREATE TABLE IF NOT EXISTS famillies (
id INTEGER PRIMARY KEY,
reference VARCHAR(32) NOT NULL,
name TEXT NOT NULL,
unit VARCHAR);`;
locationTable : string = `CREATE TABLE IF NOT EXISTS locations (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL);`;
//Date , Quantity , Unit Cost , Reason (New Stock - Usable Return - Unusable Return ) ,UPC (Universal Product Code ) Comment
transactionTable : string = `CREATE TABLE IF NOT EXISTS transactions (
id INTEGER PRIMARY KEY,
date TEXT,
quantity REAL,
unitCost REAL,
reason VARCHAR,
upc TEXT,
comment TEXT,
product_id INTEGER,
FOREIGN KEY(product_id) REFERENCES products(id));`;
async createTables(){
try {
await this.database.executeSql(this.familyTable);
await this.database.executeSql(this.locationTable);
await this.database.executeSql(this.productTable);
await this.database.executeSql(this.transactionTable);
}catch(e){
console.log("Error !");
}
}
constructor(public sqlite :SQLite) {
console.log('Hello DataServiceProvider Provider')
this.sqlite.create({name: "data.db", location: "default"}).then((db : SQLiteObject) => {
this.database = db;
}, (error) => {
console.log("ERROR: ", error);
});
}
}
Does anyone has an idea how to fix it?
Your code won't work in browser when running ionic serve, because:
As per mentioned here
Cordova needs plugins to run in browser
And they are not added by default. So you can run the project with ionic cordova run browser
OR as mentioned in the comment as well, mock the plugin. Tried it and it worked:
in app module, mock the create:
import { SQLite , SQLiteDatabaseConfig , SQLiteObject } from '#ionic-native/sqlite';
class SQLiteMock {
public create(config: SQLiteDatabaseConfig): Promise<SQLiteObject> {
return new Promise((resolve,reject)=>{
resolve(new SQLiteObject(new Object()));
});
}
}
Mark it in providers like:
{provide: SQLite, useClass: SQLiteMock},
Create a file sql.js file in the folder and copy the content from here: https://raw.githubusercontent.com/kripken/sql.js/master/js/sql.js
and add to your index.html:
<script src="assets/sql.js"></script>
<script src="build/polyfills.js"></script>
<script src="build/main.js"></script>
Now your function should work just fine. Going the further steps, I suggest you follow the link I provided before this code, i.e: https://www.techiediaries.com/mocking-native-sqlite-plugin/
One thing you could look into is whether the constructor is being run before the async function in your code. If so look into implementing something along the lines on ngOnInit.
I am using PhoneGap and WebSql. When i am trying it on browser everything is fine.SQLResultSet object has 3 property which are rows,insertId and rowsAffected.
But When i generate and Apk and trying a mobile device, SQLResultSet object has two property rows and rowsAffected.It is getting rowsAffected 0 on mobile device however it is getting 1 in browser on pc.On mobile device 'insertID' getting undefined.
db.transaction(function (t) {
t.executeSql("INSERT INTO TEST (Testname) VALUES (?)", ["test"], function (t, rresult) {
alert(JSON.stringify(rresult));
}, function (t, error) {
alert(error)
})
}, function (error) {
alert("error" + error);
},
function (success) {
alert("success" + success);
})
thanks for help.
The table creation is below.
tx.executeSql("CREATE TABLE IF NOT EXISTS TESTT (Id INTEGER PRIMARY KEY,Testname text)", [],
function (tx, results) { console.log("Successfully created") },
function (tx, error) { console.log("Could not created") }
So I'm using the most recent version of Ionic2 (v3.4) and I'm trying to get the ionic native SQLite to work. I've been able to create database file and put a table in it like so:
this.sqlite.create({
name: "data.db",
location: "default"
})
.then((db:SQLiteObject) => {
db.executeSql(tableQuery, {})
.then(() => console.log("success"))
.catch(() => console.log("fail"));
})
Inserting works too. But when I try to get the result of a selection:
this.sqlite.create({
name: "data.db",
location: "default"
})
.then((db:SQLiteObject) => {
db.executeSql("SELECT * FROM savedCoupons where itemId=" + itemId, {})
.then((db) => {console.log(JSON.stringify(db))})
.catch(() => console.log("***ERROR WITH SELECT***"));
})
.catch(() => console.log("ERROR: FAILED TO CREATE/OPEN DATABASE."));
I get lost because of the lack of documentation. JSON.stringify() is being run so it would seem the query worked. It returns {"rows":{"length":1}, "rowsAffected":0} and that's it. How do I access the result of the query?
Let you have three columns e.x id,name,lastname in your table.
after querying you can access it like:
db.executeSql('SELECT * FROM student WHERE id='+1, {})
.then(result => {
for (var i = 0; i < result.rows.length; i++) {
console.log("---Id---"+result.rows.item(i).id);
console.log("---Name---"+result.rows.item(i).name);
console.log("---Lastname---"+result.rows.item(i).lastname);
}
});
I m developing Android application. I'm integrating the sqlite into my application https://github.com/brodyspark/PhoneGap-sqlitePlugin-Android
The below error is coming
Uncaught TypeError: Object # has no method 'exec'
while using the following code
window.sqlitePlugin.openDatabase({name: "DB"});
You need to ensure you have waited for Cordova to load prior to opening a database.
As per the README.md from the project:
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase({name: "my.db"});
// ...
}
https://github.com/xuexueMaGicK/Gift-App
see this link js file is available here database connection are there
window.addEventListener("DOMContentLoaded", init);
function init() {
pageshow = document.createEvent("Event");
pageshow.initEvent("pageshow", true, true);
tap = document.createEvent("Event");
tap.initEvent("tap", true, true);
pages = document.querySelectorAll('[data-role="page"]');
numPages = pages.length;
links = document.querySelectorAll('[data-role="link"]');
numLinks = links.length;
//checkDB();
document.addEventListener("deviceready", checkDB, false);
}
/*******************************
General Interactions
*******************************/
function checkDB() {
navigator.splashscreen.hide();
database = openDatabase('data', '', 'data', 1024 * 1024);
if (database.version === '') {
database.changeVersion('', '1.0', createDB, function (tx, err) {
console.log(err.message);
}, function (tx, rs) {
console.log("Increment transaction success.");
});
addNavHandlers();
} else {
addNavHandlers();
}
}
function createDB(db)
{
/*******Create Table Gifts********/
db.executeSql('CREATE TABLE "gifts" ("gift_id" INTEGER PRIMARY KEY AUTOINCREMENT, "name_id" INTEGER, "occasion_id" INTEGER, "gift_idea" VARCHAR(45))', [], function (tx, rs) {
console.log("Table gifts created");
}, function (tx, err) {
console.log(err.message);
});
/*******Create Table Names********/
db.executeSql('CREATE TABLE "names" ("name_id" INTEGER PRIMARY KEY AUTOINCREMENT, "name_text" VARCHAR(80))', [], function (tx, rs) {
console.log("Table names created");
}, function (tx, err) {
console.log(err.message);
});
/*******Create Table Occasions********/
db.executeSql('CREATE TABLE "occasions" ("occasion_id" INTEGER PRIMARY KEY AUTOINCREMENT, "occasion_text" VARCHAR(80))', [], function (tx, rs) {
console.log("Table occasions created");
}, function (tx, err) {
console.log(err.message);
});
}
In Manifest.xml u have to add plugins related to the SQLite.Then it will work.