I am writing a mobile application for storing data locally using Sqlite. For the past 4 days, I have been trying to figure out why database is not creating when Jquery and phonegap are fully loaded. Create statement in sqlite doesn't work and callback functions are not working. The deviceready doesn't work but if checking for sqlite support it fires. The example code is someone's else code but the same thing happened. Can someone please help me?
var jqmReady = $.Deferred(),
pgReady = $.Deferred();
// jqm page is ready
$(document).bind("pageinit", jqmReady.resolve);
// phonegap ready
document.addEventListener("deviceready", pgReady.resolve, false);
// all ready, throw a custom 'onDeviceready' event
$.when(jqmReady, pgReady).then(function(){
$(document).trigger("onDeviceready");
});
function onDeviceReady(){
db.transaction(populateDB, errorCB, successCB);
}
//create table and insert some record
function populateDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS SoccerPlayer (id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT NOT NULL, Club TEXT NOT NULL)');
tx.executeSql('INSERT INTO SoccerPlayer(Name,Club) VALUES ("Alexandre Pato", "AC Milan")');
tx.executeSql('INSERT INTO SoccerPlayer(Name,Club) VALUES ("Van Persie", "Arsenal")');
}
//function will be called when an error occurred
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
//function will be called when process succeed
function successCB() {
alert("success!");
db.transaction(queryDB,errorCB);
}
I haven't run it on an emulator or physical device but from looking at the code I can see one issue right off the back. Try this and see if it helps:
Change
$.when(jqmReady, pgReady).then(function(){
$(document).trigger("onDeviceready");
});
to
$.when(jqmReady, pgReady).then(function(){
onDeviceReady();
});
The reason I suggest that change is because $(document).trigger("onDeviceready") is triggering the 'onDeviceready' event. You don't have a listener setup to catch that event and I assume what you wanted it to do is call the "onDeviceReady()" function.
Related
I tried to JSON data insert into SqLit database in PhoneGap. I created a table with two columns, like this:
function setup(tx) {
tx.executeSql('DROP TABLE IF EXISTS HEADER_DATA');
tx.executeSql("create table if not exists bookinformation(inserkey TEXT, key TEXT)");
}
This code runs successfully and the table is created. Then, I insert JSON data into the bookinformation table, like this:
function dbReady() {
db.transaction(function(tx) {
alert("5");
$.getJSON('http://echo.jsontest.com/key/value/one/two',function(data){
$.each(data, function(i, dat){
tx.executeSql('INSERT OR REPLACE INTO bookinformation (inserkey, key) VALUES("'+data.one+'", "'+data.key+'")');
alert("completed");
});
});
}, errorHandler, function() { alert('added row'); });
}
However, the insert statement fails. I get this error:
Uncaught InvalidStateError:Failed to execute 'executeSql' on 'SQLTransaction':SQL execution is disallowed
What is causing this error?
Old question but this might help others.
That error is usually caused by the transaction tx being stale.
This is because of the ajax call and by the time your ajax callback gets hit that tx object is no longer valid. The same happens if you use setTimeout or any time consuming non-Websql operation aswell.
To avoid that simply, create the transaction inside in the callback.
E.g
function dbReady() {
$.getJSON('http://echo.jsontest.com/key/value/one/two',function(data) {
db.transaction(function(tx) {
alert("5");
$.each(data, function(i, dat) {
tx.executeSql('INSERT OR REPLACE INTO bookinformation (inserkey, key) VALUES("'+data.one+'", "'+data.key+'")');
});
alert("completed");
}, errorHandler, function() { alert('added row'); });
});
}
I am making very simple application in cordova for ios/android. I have made it all but I am getting problem in database. I am trying to make sure that when app run it look for internet and if internet is available than it login using api, but it also create two databases one for user login(I know it is not good practice, but my requirement will search something to encrypt database) and save only current user in database. While other db will be used to store offline working of user. But when I am not clear how to know if my db is already made. Following are codes, kindly check, as I have search everywhere and seem like there is no solution except to check tables but when I do check tables my program stops to work.
When application start it asks userid, password than after validation following commands run.
document.addEventListener("deviceready", onDeviceReady(user, serviceURL, pass), false)
Following is function I am using on deviceready, if internet available it log in user and create db, if internet is not available it access db, but here is problem how I know if db exist so let login user otherwise alert him that internet is required for first time.
function onDeviceReady(user, serviceURL, pass) {
if(navigator.network.connection.type == Connection.NONE)
{
var db = window.openDatabase(
'test',
'1.0.0',
'Test Database',
64 * 1024
);
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM USERS', [], function (tx, results) {
var len = results.rows.length, i;
msg = "<p>Found rows: " + len + "</p>";
}
alert(msg);
for (i = 0; i < len; i++){
alert(results.rows.item(i).user );
}
}, null);
});
}
else
{
alert("Internet is available!!");
$.getJSON(serviceURL + 'APIjson.php?user='+user+'&pass='+pass+'&action=login', function(data)
{
if(data.error==-1)
{
alert("Invalid user id or password.");
return false;
}
else {
//navigator.notification.activityStop(); // for android only
// ActivityIndicator.hide(); // for IOS
window.localStorage["user_id"] = data.id;
var db = window.openDatabase(
'test',
'1.0.0',
'Test Database',
64 * 1024
);
db.transaction(function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS USERS');
tx.executeSql('CREATE TABLE IF NOT EXISTS USERS (id unique, user, pass)');
var sql = 'INSERT INTO USERS (id, user, pass) VALUES (?, ?, ?)';
tx.executeSql(sql,[data.id, user, pass]);
},function errorCB(tx, err) {
alert("Error processing SQL: "+err);
},function successCB() {
alert("success!");
});
window.location.href = "contact.html";
return true;
}
})
}
}
I also tried to add when database retrieve on len that howmany rows came and it should alert, but it failed and my app stop to work
if (!len > 0) {
alert("Sorry you need to connect internet for first time use");
return false;
You should move the javascript redirect into the success callback:
db.transaction(function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS USERS');
tx.executeSql('CREATE TABLE IF NOT EXISTS USERS (id unique, user, pass)');
var sql = 'INSERT INTO USERS (id, user, pass) VALUES (?, ?, ?)';
tx.executeSql(sql,[data.id, user, pass]);
},function errorCB(tx, err) {
alert("Error processing SQL: "+err);
},function successCB(){
alert("success!");
window.location.href = "contact.html";
});
The problem is that you are navigating away from your current page before the transaction has the chance to complete. The whole point of a call back is that it is called at a later time when the async task completes. However when you navigate away from the page, the webview will simply drop all tasks on the current page and move on.
Secondly, instead of a drop create you should use:
db.executeSql('CREATE TABLE IF NOT EXISTS tableName (someID text primary key, data text)');
To see if the data was added:
I suggest you use the chrome console to interact with the db. https://developers.google.com/chrome-developer-tools/docs/remote-debugging
You will need to write a couple db.executeSql(selectStatement) eg:
db.transaction(function(tx) {
tx.executeSql("select * from table1 where theID ='"+theID+"';", [], function(tx, rs) {
for (var i=0; i < rs.rows.length; i++) {
console.log(rs.rows.item(i));
console.log('data found in db');
}
if(rs.rows.length < 1){
console.log('data not in db');
}
},function(tx,e){console.log(e.message);});
});
To see the database, use the chrome debugger:
Connect your phone in debug mode/start emulator
In chrome go to this url: chrome://inspect/
Find your app and click inspect. A new window will open up.
Click on resources tab on top.
In the left pane click WebSQL (see screenshot)
I am inserting a row in sqlite table in phonegap using following function. My row is successfully inserted but after that it gives me error message
function executeQuery(qry_str){
var db = getDatabase();
var response = db.transaction(function(tx){
tx.executeSql(qry_str);
}, successCB, errorCB);
}
function errorCB(){
console.log('query error');
}
function successCB(){
console.log('success');
}
Please check out the mistake I am doing.
i have an application write with phonegap , i want when first time my application load , tables and data create and insert in database , but when run my application every time , insert data done again , and load time increase , how can chek if table created dont insert data again ?
document.addEventListener("deviceready", onDeviceReady, false);
var dbShell ;
function onDeviceReady() {
dbShell = window.openDatabase("BaharNarenj", "1.0", "BaharNarenj", 2000000);
dbShell.transaction(setupTable,dbErrorHandler,getEntries);
}
function setupTable(tx){
tx.executeSql("CREATE TABLE IF NOT EXISTS amaken(id INTEGER,title,des,px,py)");
tx.executeSql('insert into amaken(id,title,des,px,py) values(2,"test","dec","36.566185","55.059502")');
tx.executeSql('insert into amaken(id,title,des,px,py) values(4,"test5","dec5","36.566185","55.059502")');
}
function dbErrorHandler(err){
alert("DB Error: "+err.message + "\nCode="+err.code);
}
function getEntries() {
alert("done");
}
You can set one flag (like XApp1.0 in following code) in local storage and check that flag's value while subsequent run of the app. Hope this will help you.
function onDeviceReady() {
var firstrun = window.localStorage.getItem("XApp1.0");
if ( firstrun == null ) {
window.localStorage.setItem("XApp1.0", "1");
var db = window.openDatabase("XApp", "1.0", "XApp", 200000);
db.transaction(populateDB, errorCB, successCB);
}
else {
// Db Alredy Exists
var db = window.openDatabase("XApp", "1.0", "XApp", 200000);
db.transaction(queryDB, errorCB);
}
}
I am developing an APP using phonegap/coredava while trying to create an access database for the first time after app is installed I am unable to access database but on second run everything working fine how can I fix this my javascript code is below
var dbsize=4*1024;
document.addEventListener("deviceready", onDeviceReady, false);
var dbShell = window.openDatabase("mydb", "1.0", "my db", dbsize);
function onDeviceReady(){
dbShell.transaction(defaultPopulatedb,errorDF,successDF);
}
function defaultPopulatedb(tx){ //creating tables for the first time
tx.executeSql('CREATE TABLE IF NOT EXISTS Userlocation (id INTEGER PRIMARY KEY AUTOINCREMENT, Location TEXT NOT NULL, Locationvalue TEXT NOT NULL)',[],checkfirst,errorTB);
}
function checkfirst(tx)
{
tx.executeSql('SELECT * FROM Userlocation',[],chevals,errorDFS); }
}
function chevals(tx,result)
{
var len =result.rows.length;
if(!len){
tx.executeSql('INSERT INTO Userlocation(Location,Locationvalue) VALUES ("default","default")',[],added,erdf);
}
}
function errorDFS()
{
alert("error");
}
function added()
{
alert("added");
}
function erdf()
{
alert("error adding default");
}
function errorTB()
{
alert("error table");
}
I met this problem once too. You can just simply try{...} catch (ex){...} and ignores the first exception.
Actually, there is a great data access framework for phonegap.