Code:
/* Helpful info:
base: http://docs.phonegap.com/en/2.0.0/cordova_storage_storage.md.html#Storage
modifications: http://tv.adobe.com/watch/adc-presents/phonegap-storage-api/eng/
*/
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
var db;
function onDeviceReady() {
db = window.openDatabase("Database", "1.0", "BOOKMARKS3", 200000);
db.transaction(populateDB, errorCB, successCB);
}
// Create the database
function populateDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS BOOKMARKS3 (id INTEGER NOT NULL, filename TEXT NOT NULL, title TEXT NOT NULL)');
}
// 1. Transaction error callback (corrected per Sitepoint.com post)
function errorCB(tx, err) {
alert('Error processing SQL: ' + err);
}
// 2. Transaction success callback
function successCB() {
var db = window.openDatabase("Database", "1.0", "BOOKMARKS3", 200000);
db.transaction(queryDB, errorCB);
}
// 3. Add row via button on external page
function insertRow() {
db = window.openDatabase("Database", "1.0", "BOOKMARKS3", 200000);
db.transaction(function(tx) {
var id, filename = window.location.pathname, title = document.title;
tx.executeSql("insert into BOOKMARKS3(id, filename, title) values(?,?,?)", [id, filename, title]);
}, errorCB, successCB()); alert('Bookmark added.');
}
// 4. Display the rows on this page (onLoad)
function querySuccess(tx, results) {
var len = results.rows.length;
console.log("BOOKMARKS3 table: " + len + " rows found.");
for (var i=0; i<len; i++) {
rowId = results.rows.item(i).id;
document.getElementById("output").innerHTML +="<div class='row'>" +
"<a href='" + results.rows.item(i).filename + "'><input type='button' class='buttonBM' value='" + results.rows.item(i).title + "'></a></div>" +
'<div class="buttonRemove"><input type="button" class="buttonEdit" value="Remove" onclick="removeRow(\'' + rowId + '\')"></div>';
} document.getElementById("output").innerHTML +="<div class='row'><p style='line-height:2em;'>You have " + len + " BOOKMARKS3.</p></div>";
}
// 5. Query the DB
function queryDB(tx) {
tx.executeSql("SELECT * FROM BOOKMARKS3", [], querySuccess, errorCB);
}
// 6. Remove row via button on this page
function removeRow() {
db = window.openDatabase("Database", "1.0", "BOOKMARKS3", 200000);
var rowId;
db.transaction(function(tx) {
tx.executeSql("delete from BOOKMARKS3 where id='" + rowId + "'");
}, errorCB, successCB()); alert('Bookmark removed.');
} exit;
// Cordova is ready
function onDeviceReady() {
var db = window.openDatabase("Database", "1.0", "BOOKMARKS3", 200000);
db.transaction(populateDB, errorCB, successCB);
}
Bookmarks