I am trying to create a database using phonegap's api:
In order to do this I have used the following html:
<!DOCTYPE HTML>
<html>
<head>
<title>Cordova</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
var db = window.openDatabase("test", "1.0", "Test DB", 1000000);
alert("database created");
}
</script>
</head>
<body>
<form name="input" action="html_form_action.asp" method="get">
<input type="submit" value="Create Db" />
</form>
</body>
</html>
The buttone doesnt do anyting. The idea is that when the app starts I'm supposed to get confirmation that a database has been created. However this is not happening. Please help...
**Hi check whether Deviceready fires or not then try this **
function onDeviceReady() {
alert("onDeviceReady");
try {
if (!window.openDatabase) {
alert('Browser does not Support this');
} else {
var shortName = 'DbName';
var version = '1.0';
var displayName = 'DBName';
var maxSize = 100000; // in bytes
openDatabase(shortName, version, displayName, maxSize);
alert('DB created');
}
} catch(e) {
if (e == 2) {
// Version mismatch..
console.log("Invalid database version.");
} else {
console.log("Unknown error "+ e +".");
}
return;
}
}
I think there is problem in your js location path . I run your code and i didn't get any error.
Please check your path of your cordova.js . I think you put that js in js folder of assets/www/js
I dont think 'alert()' works inside a webview as-is. Try console.log() instead to output a message (if you are using eclipse), or some other method - perhaps changing the content of a div - to show you the results.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
hi i am new to phonegap .. i try using phonegap with database now, i am able to display the records in emulator / fetch record .. but when i try to build the application in build.phonegap.com to make .apk when i install the application and run in my android no record display .. my question is how can i build my application including the database ? i have .db already where should i place it or something do i need to add some script ? hope u get my point and sorry for my english..
here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Storage Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.4.0.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
}
function clickFunc(){
var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
db.transaction(selectData);
}
function selectData(tx){
tx.executeSql("SELECT * FROM test",[],resultSuccess,resultError);
}
function resultError(error){
alert("Error: "+error);
}
function resultSuccess(tx, response){
var div = document.getElementById('display');
var tmp = "<table><tr><th>ID</th><th>DATA</th></tr>";
for(var i = 0;i<response.rows.length;i++){
tmp += "<tr><td>" + response.rows.item(i).id + "</td><td>" + response.rows.item(i).data + "</td></tr>";
div.innerHTML = tmp;
}
}
</script>
</head>
<body>
<input type="button" value="FITCH" id="btnSelect" onclick="clickFunc();"/>
<div id="display">
</div>
Your create only database but your not create any table and nothing to insert it. So that your apk doesn't produce your excepted result.
So you will try this code
<!DOCTYPE html>
<html>
<head>
<title>Storage Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.4.0.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
}
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS DEMO');
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
}
function clickFunc(){
var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
db.transaction(selectData);
}
function selectData(tx){
tx.executeSql("SELECT * FROM test",[],resultSuccess,resultError);
}
function resultError(error){
alert("Error: "+error);
}
function resultSuccess(tx, response){
var div = document.getElementById('display');
var tmp = "<table><tr><th>ID</th><th>DATA</th></tr>";
for(var i = 0;i<response.rows.length;i++){
tmp += "<tr><td>" + response.rows.item(i).id + "</td><td>" + response.rows.item(i).data + "</td></tr>";
div.innerHTML = tmp;
}
}
</script>
</head>
<body>
<input type="button" value="FITCH" id="btnSelect" onclick="clickFunc();"/>
<div id="display">
</div>
If you need more details please refer this link: http://docs.phonegap.com/en/2.7.0/cordova_storage_storage.md.html#Storage
I am new to phone gap.I am referring examples from http://docs.phonegap.com/.
But when i am trying to execute the program given in http://docs.phonegap.com/en/1.8.1/cordova_contacts_contacts.md.html#Contacts
the onDeviceReady function is not getting loaded.
**Case 1:**
**Here is the code(index.html file):**
<!DOCTYPE html>
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.8.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
alert("onDeviceReady");
console.log("onDeviceReady");
// create
var contact = navigator.contacts.create();
contact.displayName = "Plumber";
contact.nickname = "Plumber"; //specify both to support all devices
var name = new ContactName();
name.givenName = "Jayshree";
name.familyName = "Barkur";
contact.name = name;
// save
contact.save(onSaveSuccess,onSaveError);
// clone
//var clone = contact.clone();
// clone.name.givenName = "John";
// console.log("Original contact name = " + contact.name.givenName);
//console.log("Cloned contact name = " + clone.name.givenName);
// remove
//contact.remove(onRemoveSuccess,onRemoveError);
}
// onSaveSuccess: Get a snapshot of the current contacts
//
function onSaveSuccess(contact) {
alert("Save Success");
}
// onSaveError: Failed to get the contacts
//
function onSaveError(contactError) {
alert("Error = " + contactError.code);
}
// onRemoveSuccess: Get a snapshot of the current contacts
//
function onRemoveSuccess(contacts) {
alert("Removal Success");
}
// onRemoveError: Failed to get the contacts
//
function onRemoveError(contactError) {
alert("Error = " + contactError.code);
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Create Contacts</p>
</body>
</html>
I am executing this program in eclipse(Android 4.4).On execution the emmulator only shows
**Examples**
**Create Contacts**
And nothing happens after that i.e the the onDeviceReady method is not called and neither the other callback functions are called.
**Case 2:**
When i am adding an extra line in the program i.e. <p>Add Contact</p> in the body section,The contacts are getting added.
But
function onSaveSuccess(contact) {
alert("Save Success");
}
does not works for me.
**Here goes my code(index.html file):**
<!DOCTYPE html>
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.8.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
alert("onDeviceReady");
console.log("onDeviceReady");
// create
var contact = navigator.contacts.create();
contact.displayName = "Plumber";
contact.nickname = "Plumber"; //specify both to support all devices
var name = new ContactName();
name.givenName = "Jayshree";
name.familyName = "Barkur";
contact.name = name;
// save
contact.save(onSaveSuccess,onSaveError);
// clone
//var clone = contact.clone();
// clone.name.givenName = "John";
// console.log("Original contact name = " + contact.name.givenName);
//console.log("Cloned contact name = " + clone.name.givenName);
// remove
//contact.remove(onRemoveSuccess,onRemoveError);
}
// onSaveSuccess: Get a snapshot of the current contacts
//
function onSaveSuccess(contact) {
alert("Save Success");
}
// onSaveError: Failed to get the contacts
//
function onSaveError(contactError) {
alert("Error = " + contactError.code);
}
// onRemoveSuccess: Get a snapshot of the current contacts
//
function onRemoveSuccess(contacts) {
alert("Removal Success");
}
// onRemoveError: Failed to get the contacts
//
function onRemoveError(contactError) {
alert("Error = " + contactError.code);
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Create Contacts</p>
<p>Add Contact</p>
</body>
</html>
Kindly let me know the reason behind this and suggest some solution to solve this problem.
Thanks in advance
Seems like you havent added the cordova library
download the same from here and add cordova-1.8.0.js to the www folder
Try this :
Enable the emulator GPU.
In Eclipse go to Window -> AVD Manager select your AVD and click "Edit".
Check "Use Host GPU" box, then save and restart your AVD.
Hope this helps.
I was trying some cookbook samples of phonegap app(along with xui) to read write files to local storage(SD card), PhoneGap is so popular in its file io, but when I tried on the device it didn't do anything. I think somebody has encountered same things.
The code is shown below:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width;" />
<title>File Download</title>
<script type="text/javascript" src="xui.js"></script>
<script type="text/javascript" src="cordova-2.0.0.js"></script>
<script type="text/javascript" >
var downloadDirectory;
document.addEventListener("deviceready", onDeviceReady, true);
function onDeviceReady() {
window.requestFileSystem(
LocalFileSystem.PERSISTENT,
0,
onFileSystemSuccess,
null
);
x$('#download_btn').on( 'click', function(e) {
download();
});
}
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getDirectory('my_downloads',{create:true},
function(dir) {
downloadDirectory = dir;
},fail);
}
function fail(error) {
x$('#message').html('We encountered a problem: ' + error.code);
}
function download() {
var fileURL = document.getElementById('file_url').value;
var localFileName = getFilename(fileURL);
x$('#message').html('Downloading ' + localFileName);
var fileTransfer = new FileTransfer();
fileTransfer.download(fileURL, downloadDirectory.fullPath + '/' + localFileName,
function(entry){
x$('#message').html('Download complete. File saved to: ' + entry.fullPath);
},
function(error){
alert("Download error source " + error.source);
}
);
}
// Obtain the filename
function getFilename(url) {
if (url) {
var m = url.toString().match(/.*\/(.+?)\./);
if (m && m.length > 1) {
return m[1] + '.' + url.split('.').pop();
}
}
return "";
}
</script>
</head>
<body>
<input type="text" id="file_url" value="http://blogs.adobe.com/adobeingovernment/files/2012/07/phonegap.jpg" />
<input type="button" id="download_btn" value="Download" />
<div id="message"></div>
</body>
</html>
I already reviewed android manifest file, it has all permission including write to external storage. Kindly advise.
I am a total beginner with Phonegap/cordova so bear with me.
I have a blank application that I would like to connect to a database and display the results. Below is my code..
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="jquery.mobile-1.4.2.css" />
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.4.2.js"></script>
<script type="text/javascript">
//add listener when device ready
document.addEventListener("deviceready", onDeviceReady, false);
var db = window.openDatabase("Dummy_DB", "1.0", "Just a Dummy DB", 0); //will create database Dummy_DB or open it
//function will be called when device ready
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);
}
//select all from SoccerPlayer
function queryDB(tx){
tx.executeSql('SELECT * FROM SoccerPlayer',[],querySuccess,errorCB);
}
function querySuccess(tx,result){
$('#SoccerPlayerList').empty();
$.each(result.rows,function(index){
var row = result.rows.item(index);
$('#SoccerPlayerList').append('<li><h3 class="ui-li-heading">'+row['Name']+'</h3><p class="ui-li-desc">Club '+row['Club']+'</p></li>');
});
$('#SoccerPlayerList').listview();
}
</script>
</head>
<body>
<div data-role="page">
<div data-role="header" data-position="fixed" data-theme="b">
<h1>Soccer Player</h1>
</div>
<div data-role="content">
<ul id="SoccerPlayerList">
</ul>
</div>
</div>
<!--end of Soccer Player Page--->
</body>
</html>
The code doesn't seem to create or read any database at all. When I load the application onto my android phone it shows no results, even when I load it in a browser it loads no results.
I am not getting any console errors, but I do get an error in my LogCat error opening trace file: No such file or directory (2).
Am I missing something to make the database connections work? Or is there something that I can't seem to find in my code that is wrong?
Change this:
//add listener when device ready
document.addEventListener("deviceready", onDeviceReady, false);
var db = window.openDatabase("Dummy_DB", "1.0", "Just a Dummy DB", 0); //will create database Dummy_DB or open it
//function will be called when device ready
function onDeviceReady(){
db.transaction(populateDB, errorCB, successCB);
}
TO:
//add listener when device ready
document.addEventListener("deviceready", onDeviceReady, false);
var db;
//function will be called when device ready
function onDeviceReady(){
db = window.openDatabase("Dummy_DB", "1.0", "Just a Dummy DB", 0); //will create database Dummy_DB or open it
db.transaction(populateDB, errorCB, successCB);
}
You need to wait for the deviceReady call be for defining your database.
In my application, i want to insert the value in the table. i have created the databse in onDeviceReady() method in the index.html file.
<!DOCTYPE html>
<!-- Auto Generated with Sencha Architect -->
<!-- Modifications to this file will be overwritten. -->
<html>
<head>
<meta name="generator" content="HTML Tidy, see www.w3.org">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Teritree</title>
<script type="text/javascript" id="phonegap" src=
"cordova-2.0.0.js">
</script>
<script type="text/javascript" src="barcodescanner.js">
</script>
<script src="sencha-touch-all.js" type="text/javascript">
</script>
<link rel="stylesheet" type="text/css" href="app.css">
<script type="text/javascript" src="app/Ext.ux.touch.Rating.js">
</script>
<script type="text/javascript" src="app/app.js">
</script>
<script type="text/javascript">
Ext.Loader.setConfig({ disableCaching: false });
Ext.Ajax.setDisableCaching(false);
</script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
var mydb;
// Wait for PhoneGap to connect with the device
function onLoad() {
document.addEventListener("deviceready",onDeviceReady,false);
}
// PhoneGap is ready to be used!
function onDeviceReady() {
console.log("it is in ondevice ready method..");
mydb = window.openDatabase("teritreeDb", "1.0", "TestDB", 10000);
console.log("it is in ondevice ready method..1");
mydb.transaction(populateDB, errorCB, successCB);
console.log("it is in ondevice ready method..2");
}
function populateDB(tx) {
console.log("it is in populateDB----------1");
tx.executeSql('DROP TABLE IF EXISTS DEMO', function () {
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)', function () {
console.log("Table created");
});
});
// Transaction error callback
//
function errorCB(tx, err) {
alert("Error processing SQL: "+err);
}
// Transaction success callback
//
function successCB() {
alert("success!");
}
}
</script>
<script type="text/javascript">
if (!Ext.browser.is.WebKit) {
alert("The current browser is unsupported.\n\nSupported browsers:\n" +
"Google Chrome\n" +
"Apple Safari\n" +
"Mobile Safari (iOS)\n" +
"Android Browser\n" +
"BlackBerry Browser"
);
}
</script>
</head>
<body>
</body>
</html>
Now i have one signup screen and there in the signup screen i have submit button. So if i click the submit button, all the details should store in the database means in the DEMO table..So in the controller, i am writing the button event,
onSubmitButtonTap : function(button, e, options) {
mydb = window.openDatabase("appDb", "1.0", "Test DB", 1000000);
mydb.transaction(storeCustomerDetails, error, success);
function storeCustomerDetails(tx)
{
tx.executeSql('insert into DEMO (id,data) values("1","Hello")');
tx.executeSql('insert into DEMO (id,data) values("2","Hello World")');
}
function error(){
alert("data is not inserted");
}
function success(){
alert("data is succesfully inserted");
}
},
but it is giving me the alert, data is not inserted.
I followed the link: Phonegap DB Link
Please help..
Use Cordova 2.0.0 and your issue will be solved.. You will be able to see the database you created in the file explorer. Do let me know if it helps you.
Arindam, do not forget by default the executing of the sql is asyncronious. Therefore nobody warranty your sqls will be executed in order you have defined in function populateDB(tx). Eg. it could execute first create than delete...
To be sure in the order you have to define subsequent calls in the callback function
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS DEMO', function () {
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)', function () {
console.log("Table created");
});
});
}
Cheers, Oleg