Trying to execute code on device ready - javascript

I am trying to execute some Javascript code on deviceready by using a listener.
It doesn't seem to be calling the code - I'm getting nothing in my console, and none of the variables are set.
This is the code example I'm using:
<script>
// Cordova is ready
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase({name: "my.db"});
db.transaction(function(tx) {
tx.executeSql('DROP TABLE IF EXISTS test_table');
tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');
tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) {
console.log("insertId: " + res.insertId + " -- probably 1");
console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");
tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) {
console.log("res.rows.length: " + res.rows.length + " -- should be 1");
console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1");
});
}, function(e) {
console.log("ERROR: " + e.message);
});
});
}
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
</script>
Now, I'm not primarily a Javascript developer (so this question may be simple), but is there some reason why the code is not executing? Do I have to run it in an anonymous function?
How do I get the onDeviceReady() function to execute?

deviceready is a special Cordova event; unless you launch your code in a Cordova environment, the event will never get fired (and your code will never get executed).
You can run Cordova in the browser by adding the browser as a platform. For more info, see http://www.raymondcamden.com/2014/09/24/Browser-as-a-platform-for-your-PhoneGapCordova-apps.
You could also use something like Ripple to emulate the Cordova environment in Chrome.

Since Cordova-SQLitePlugin API is asynchronous, you should execute transaction after the db is available/created. Try to implement it in a similar way as below:
var openDb = function (name, ok, error) {
try {
// SQLitePlugin always uses callbacks to specify the status of 'open' operation
var dbRef = window.sqlitePlugin.openDatabase({name: name},
function (db) {
log("DataBase " + name + " opened!");
ok(db);
}, function (e) {
try {
dbRef.close();
} catch (e) {
log("Could not close database", e);
}
error(e);
});
} catch (e) {
log("Could not open " + name + " DataBase");
error(e);
}
};
openDb("my.db", function(db){
db.transaction(function(tx) {
tx.executeSql('DROP TABLE IF EXISTS test_table');
tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');
tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) {
console.log("insertId: " + res.insertId + " -- probably 1");
console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");
tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) {
console.log("res.rows.length: " + res.rows.length + " -- should be 1");
console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1");
});
}, function(e) {
console.log("ERROR: " + e.message);
});
});
});

Related

How to populate Parameter in $cordovaSQLite as my own array

I used this codes to execute $cordovaSQLite insert.
var qst_master_content_data= {
qst_cnt_id :content.qst_cnt_id,
question_id :content.question_id,
qst_cnt_text :content.qst_cnt_text,
qst_cnt_options :content.qst_cnt_options,
qst_story:content.qst_story,
explanation :content.explanation,
lang_id :content.lang_id,
img_id :content.img_id,
dt_update :content.dt_update
};
var query = "INSERT INTO qst_master_content ( "+
"qst_cnt_id, "+
"question_id, "+
"qst_cnt_text, "+
"qst_cnt_options, "+
"qst_story, "+
"explanation, "+
"lang_id, "+
"img_id, "+
"dt_update "+
") VALUES (?,?,?,?,?,?,?,?,?)";
$cordovaSQLite.execute(db, query, qst_master_content_data).then(function(res)
{
console.log(res);
},
function(err)
{
console.log(err);
}
Unfortunately the insert was not successfully inserted.
I was tried to use qst_master_cotent = [1,2,3]; then it would be ok.
But this not make my codes to be reuse on that format. It should be:
var qst_master_content_data= {
qst_cnt_id :content.qst_cnt_id,
question_id :content.question_id,
qst_cnt_text :content.qst_cnt_text,
qst_cnt_options :content.qst_cnt_options,
qst_story:content.qst_story,
explanation :content.explanation,
lang_id :content.lang_id,
img_id :content.img_id,
dt_update :content.dt_update
};
So that I can manipulate the data in the future. How I can do that?
Be carefull about variable names. Your parameter object name is qst_master_cotent.
It should be like this:
$cordovaSQLite.execute(db, query, qst_master_cotent)
Use this piece of code
var db = window.sqlitePlugin.openDatabase({
name: "your.db"
});
db.transaction(populateClientDB, error, success);
function populateClientDB(tx) {
tx.executeSql("INSERT INTO qst_master_content (qst_cnt_id, question_id, qst_cnt_text, qst_cnt_options, qst_story, explanation, lang_id, img_id, dt_update) \n\
VALUES (?,?,?,?,?,?,?,?,?)", [qst_master_cotent.qst_cnt_id, qst_master_cotent.question_id, qst_master_cotent.qst_cnt_text, qst_master_cotent.qst_cnt_options, qst_master_cotent.qst_story, qst_master_cotent.explanation, qst_master_cotent.lang_id, qst_master_cotent.img_id, qst_master_cotent.dt_update], function(tx, res) {
console.log("insertId: " + res.insertId + " -- probably 1");
console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");
});
}
function error(error) {
console.log(error);
}
function success() {
}
Thanks

Uncaught ReferenceError: errorHandler is not defined at file

i'm getting the error : Uncaught ReferenceError: errorHandler is not defined at file:
what am i doing wrong? source code: http://pastebin.com/3203ynUB
i iniate the first piece with onclick="startBackup()"
it seems to go wrong somewhere in retrieving data from the database, but i cant figure out how and where.
the database is as following
DBName: SmartPassDB
Table name: SmartPass
rows: id , name , nickName , passID , Website
// change to your database
var db = window.openDatabase("Database", "1.0", "SmartPassDB", 5*1024); // 5*1024 is size in bytes
// file fail function
function failFile(error) {
console.log("PhoneGap Plugin: FileSystem: Message: file does not exists, isn't writeable or isn't readable. Error code: " + error.code);
alert('No backup is found, or backup is corrupt.');
}
// start backup (trigger this function with a button or a page load or something)
function startBackup() {
navigator.notification.confirm('Do you want to start the backup? This will wipe your current backup. This action cannot be undone.', onConfirmBackup, 'Backup', 'Start,Cancel');
}
// backup confirmed
function onConfirmBackup(button) {
if(button==1) {
backupContent();
}
}
// backup content
function backupContent() {
db.transaction(
function(transaction) {
transaction.executeSql(
// change this according to your table name
'SELECT * FROM SmartPass;', null,
function (transaction, result) {
if (result.rows.length > 0) {
var tag = '{"items":[';
for (var i=0; i < result.rows.length; i++) {
var row = result.rows.item(i);
// expand and change this according to your table attributes
tag = tag + '{"id":"' + row.attribute1 + '","name":"' + row.attribute2 + '","nickName":"' + row.attribute3 + '","passId":"' + row.attribute4 + '","website":"' + row.attribute5 + '"}';
if (i+1 < result.rows.length) {
tag = tag + ',';
}
}
tag = tag + ']}';
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
// Change the place where your backup will be written
fileSystem.root.getFile("backup.txt", {create: true, exclusive: false}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.write(tag);
}, failFile);
}, failFile);
}, failFile);
alert("Backup done.");
} else {
alert("No content to backup.");
}
},
errorHandler
);
}
);
}
// start restore (trigger this function with a button or a page load or something)
function startRestore() {
navigator.notification.confirm('Do you want to start the restore? This will wipe your current data. This action cannot be undone.', onConfirmRestore, 'Restore', 'Start,Cancel');
}
// restore confirmed
function onConfirmRestore(button) {
if(button==1) {
restoreContent();
}
}
// restore content
function restoreContent() {
db.transaction(
function(transaction) {
transaction.executeSql(
// change this according to your table name
'DELETE FROM SmartPass', startRestoreContent()
);
});
}
// actually start restore content
function startRestoreContent() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
// Change the place where your backup is placed
fileSystem.root.getFile("backup.txt", null, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
var data = JSON.parse(evt.target.result);
var items = data.items;
count = items.length;
db.transaction(
function(transaction) {
$.each(items, function(index, item) {
transaction.executeSql(
// change and expand this according to your table name and attributes
'INSERT INTO SmartPass (id, name, nickName, passId, website) VALUES (?, ?, ?, ?, ?)',
[item.attribute1, item.attribute2, item.attribute3, item.attribute4, item.attribute5],
null
);
});
});
};
reader.readAsText(file);
alert("Restore done.");
}, failFile);
}, failFile);
}, failFile);
}
As per the error
error : Uncaught ReferenceError: errorHandler is not defined at file:
The function errorHandler is not defined in the code.
In your function backupContent() {..} you have used errorHandler as callback reference for the transaction.executeSql() call.
transaction.executeSql(....,errorHandler)
You need to define the errorHandler function.
Also you need to consider a scenario as to how do you handle initial database load. If you run the code for the first time there will not be any tables. The following sql statement will fail.
SELECT * FROM SmartPass;
The table SmartPass is not yet created. That is the most likely reason of the errorHandler being called.

Phonegap- insert data in online and show it in offline using database

i want to insert data in database when the device is online ,if the device is offline i want to show the data which is stored in database.
currently here i parse the data from rss feed and insert the data in database when the device is online and i cannot show the same data when the device is become offline.And also i tried lot of times to show the data in offline,using the following code:
document.addEventListener("offline", yourCallbackFunction, false);
$.each(data.responseData.feed.entries, function (e, item) {
var titles=item.title;
var linked=item.link;
s += '<li><div class="itemTitle"><a href="' + item.link + '" target="' + def.TitleLinkTarget + '" >' + item.title + "</a></div>";
if (def.ShowPubDate) {
i = new Date(item.publishedDate);
s += '<div class="itemDate">' + i.toLocaleDateString() + "</div>";
}
if (def.ShowDesc) {
if (def.DescCharacterLimit > 0 && item.content.length > def.DescCharacterLimit) {
s += '<div class="itemContent">' + item.content.substr(0, def.DescCharacterLimit) + "...</div>";
}
else {
s += '<div class="itemContent">' + item.content + "</div>";
console.log(s);
}
}
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Populate the database
//
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS DEMO');
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (title, desc)');
tx.executeSql('INSERT INTO DEMO (title, desc) Values(?,?)',[titles,s]);
}
// Query the database
//
function queryDB(tx) {
tx.executeSql('SELECT * FROM DEMO', [], querySuccess, errorCB);
}
// Query the success callback
//
function querySuccess(tx, results) {
var len = results.rows.length;
console.log("DEMO table: " + len + " rows found.");
for (var i=0; i<len; i++){
console.log("Row = " + i + " ID = " + results.rows.item(i).title + " Data = " + results.rows.item(i).desc);
$("#apps ul").append('<li><span class="tab">' +results.rows.item(i).desc+'</span></li>');
}
}
document.addEventListener("offline", querySuccess, false);
did you fire the event from the "ondeviceready" callback? i ask because this is a common mistake, but you need show us your code if you want anyone to be able to see whats wrong.
anyway, you can alaways use the navigator.connection.type property, and if you feel like reinventing the wheel you can bind your callback function to an event fired when connection.type is none. for more details:
http://docs.phonegap.com/en/2.9.0/cordova_connection_connection.md.html#Connection
also:
did you check if the data actually stored on you local db?
try to see exactly where the problem is before asking for arbitrary help.
as i thought, added the offline event listener before the device was ready, meaning before the functnionality needed to add event listener was loaded from your phonegap file. the correct way to write it is:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady(){
document.addEventListener("offline", querySuccess, false);
}

Check if DB exists and dropping DB in SQLlite IOS

I'm currently using phonegap to create and ios app.
While getting familiar to the sql javascript interactions I seem to have created 10 versions of the same named database file.
I'm currently using the following creation code (from the phonegap wiki)
var mydb=false;
// initialise the database
initDB = function() {
try {
if (!window.openDatabase) {
alert('not supported');
} else {
var shortName = 'phonegap';
var version = '1.0';
var displayName = 'PhoneGap Test Database';
var maxSize = 65536; // in bytes
mydb = openDatabase(shortName, version, displayName, maxSize);
}
} catch(e) {
// Error handling code goes here.
if (e == INVALID_STATE_ERR) {
// Version number mismatch.
alert("Invalid database version.");
} else {
alert("Unknown error "+e+".");
}
return;
}
}
// db error handler - prevents the rest of the transaction going ahead on failure
errorHandler = function (transaction, error) {
// returns true to rollback the transaction
return true;
}
// null db data handler
nullDataHandler = function (transaction, results) { }
my problem is that I'm unsure how to check if the database exists before creating it or how to create it only once per device?
and secondly how can i drop all these databases that have been created.
transaction.executeSql('DROP DATABASE phonegap;');
does not seem to drop anything.
Thanks
Please try following code. it is not creating multiple database files, just cross verify by visiting location -/Users/{username}/Library/Application Support/iPhone Simulator/4.3/Applications/{3D5CD3CC-C35B-41B3-BF99-F1E4B048FFFF}/Library/WebKit/Databases/file__0
This is sqlite3 example which cover create, insert, delete and drop queries on Table.
<!DOCTYPE html>
<html>
<body style="font: 75% Lucida Grande, Trebuchet MS">
<div id="content"></div>
<p id="log" style="color: gray"></p>
<script>
document.getElementById('content').innerHTML =
'<h4>Simple to do list</h4>'+
'<ul id="results"></ul><div>Handle Database in Phonegap</div>'+
'<button onclick="newRecord()">new record</button>'+
'<button onclick="createTable()">create table</button>' +
'<button onclick="dropTable()">drop table</button>';
var db;
var log = document.getElementById('log');
db = openDatabase("DBTest", "1.0", "HTML5 Database API example", 200000);
showRecords();
document.getElementById('results').addEventListener('click', function(e) { e.preventDefault(); }, false);
function onError(tx, error) {
log.innerHTML += '<p>' + error.message + '</p>';
}
// select all records and display them
function showRecords() {
document.getElementById('results').innerHTML = '';
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM Table1Test", [], function(tx, result) {
for (var i = 0, item = null; i &lt result.rows.length; i++) {
item = result.rows.item(i);
document.getElementById('results').innerHTML +=
'<li><span contenteditable="true" onkeyup="updateRecord('+item['id']+', this)">'+
item['id']+' '+item['text'] + '</span> x</li>';
}
});
});
}
function createTable() {
db.transaction(function(tx) {
tx.executeSql("CREATE TABLE Table1Test (id REAL UNIQUE, text TEXT)", [],
function(tx) { log.innerHTML = 'Table1Test created' },
onError);
});
}
// add record with random values
function newRecord() {
var num = Math.round(Math.random() * 10000); // random data
db.transaction(function(tx) {
tx.executeSql("INSERT INTO Table1Test (id, text) VALUES (?, ?)", [num, 'Record:'],
function(tx, result) {
log.innerHTML = 'record added';
showRecords();
},
onError);
});
}
function updateRecord(id, textEl) {
db.transaction(function(tx) {
tx.executeSql("UPDATE Table1Test SET text = ? WHERE id = ?", [textEl.innerHTML, id], null, onError);
});
}
function deleteRecord(id) {
db.transaction(function(tx) {
tx.executeSql("DELETE FROM Table1Test WHERE id=?", [id],
function(tx, result) { showRecords() },
onError);
});
}
// delete table from db
function dropTable() {
db.transaction(function(tx) {
tx.executeSql("DROP TABLE Table1Test", [],
function(tx) { showRecords() },
onError);
});
}
</script>
</body>
</html>
And about Droping Database...
Does not seem meaningful for an embedded database engine like SQLite. To create a new database, just do sqlite_open(). To drop a database, simply delete the file.
thanks,
Mayur
Manually deleting the SQLite database from the Library worked for me. Thanks for the precious tip.

Phonegap-Android-sqlite using Javascript. How to connect?

I am new to Android-Phonegap dev. I am creating a project using Eclipse in Windows XP.
I am using sqlite database. I saw the sample code in the docs. But I'm not able to execute this example. I am not getting the required results.
Suppose I want to get all the entries in the table demo in tabular format, HTML. What will the code be in index.html? For that, what is the procedure and what is the step by step procedure for doing this? Or else any better tutorials which help me to do this?
Thanks in Advance
Dnyan.
in main.js you add this
rowsDataHandler = function(transaction, results) {
// Handle the results
var html = "<ul>";
for (var i=0; i<results.rows.length; i++) {
var row = results.rows.item(i);
html += '<li>'+row['data']+'</li>\n';
}
html +='</ul>';
document.getElementById("mydata").innerHTML = html;
}
// load the currently selected icons
loadRows = function(db) {
try {
db.executeSql('SELECT * FROM DEMO',[], rowsDataHandler, errorCB);
} catch(e) {alert(e.message);}
}
in index.html you add this row inside body
<div id="mydata"></div>
One thing to bear in mind is that if you aren't testing the application on a device or in an emulator, but rather in a browser like Chrome or Safari,
document.addEventListener("deviceready", onDeviceReady, false);
won't work. What I've done is to comment out this line and just to put in a call to
onDeviceReady();
When I then test in the emulator I uncomment the "document…" line and comment out
onDeviceReady();
**html**
<input id="show" type="button" value="Show">
**js**
function globalError(tx, error)
{
alert("Error: " + error.message);
}
var db = window.openDatabase('TabOrder', '', 'Bar Tab Orders', 2500000);
db.transaction(function(tx) {
tx.executeSql('DROP TABLE IF EXISTS SubmiteData;', null, null, globalError);
tx.executeSql('CREATE TABLE IF NOT EXISTS SubmiteData (SubmiteDataId integer
primary key, UserId text, AuthNo number, LocId number,ProdId number,
CardId number, OrgLat text, OrgLng text, OrgTime text)',
null,
function()
{
SubmiteData("USER1",12345678,23434, 21212, 220232,
"9", "45", "23/06/2014");
},
globalError);
});
function SubmiteData(UserId, AuthNo, LocId,ProdId, CardId, OrgLat, OrgLng, OrgTime){
db.transaction(function(tx){
tx.executeSql('INSERT INTO SubmiteData(UserId, AuthNo, LocId, ProdId, CardId,
OrgLat, OrgLng, OrgTime) VALUES (?,?,?,?,?,?,?,?)', [UserId, AuthNo, LocId,
ProdId, CardId, OrgLat, OrgLng, OrgTime],
null,
globalError
);
});
}
function read(UserId, AuthNo, LocId,ProdId, CardId, OrgLat, OrgLng, OrgTime){
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM SubmiteData',
[],
function(tx, results)
{
for (var i=0; i<results.rows.length; i++)
{
var row=results.rows.item(i);
// alert("Id: " + row['UserId']);
var stringout = "LocId: " + row['LocId'] + "\n";
alert(stringout);
}
},
globalError
);
});
};
$(function()
{
$('#show').click(read);
});
this is the method to connect to a db using javascript
db = openDatabase("bprueba","1.0","Prueba_db",5*1023*1024);
SQL Statement Error Callback Reference

Categories

Resources