I am new to mobile application development with PhoneGap. I have created a form to add and show name, address and phone number of a student in SQLite database. But the problem is I don't know to retrieve and display the values in the text boxes.
<!DOCTYPE HTML>
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}
function populateDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (sname ,saddress ,sphone)');
}
function errorCB(tx, err) {
alert("Error processing SQL: "+err);
}
// Transaction success callback
//
function successCB() {
alert("success!");
}
function add(tx){
var name=document.getElementById('n');
var address=document.getElementById('a');
var phone=document.getElementById('p');
tx.executeSql('INSERT INTO DEMO (sname ,saddress ,sphone) VALUES ('"+name+"','"+address+"','"+phone+"')');
//tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
}
function show(tx){
var name=document.getElementById('n');
tx.executeSql('SELECT * FROM DEMO WHERE (sname='"+name+"')');
document.f.n.value=name;
document.f.a.value=//??;
document.f.p.value=//??;
}
</script>
</head>
<body>
<form name="f" method="get" action="">
Name :<input type="text" id="n" size="10"></input><br>
Add :<input type="text" id="a" size="10"></input><br>
Phone :<input type="text" id="p" size="10"></input><br>
<input type="button" value="Add" onClick="add()">
<input type="button" value="Show" onClick="show()">
</form>
</body>
</html>
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady()
{
alert("onDeviceReady called");
}
function populateDB(tx)
{
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (sname ,saddress ,sphone)');
var name=document.getElementById('n');
var address=document.getElementById('a');
var phone=document.getElementById('p');
tx.executeSql('INSERT INTO DEMO (sname ,saddress ,sphone) VALUES ('"+name.value+"','"+address.value+"','"+phone.value+"')');
}
function errorCB(tx, err)
{
alert("Error processing SQL: "+err);
}
// Transaction success callback
//
function successCB()
{
alert("success!");
}
function add()
{
var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}
for more see link here
//show data from db
// Transaction success callback
function show()
{
var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(queryDB, errorCB);
}
// 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 + " sname = " + results.rows.item(i).sname + " saddress = " + results.rows.item(i).saddress);
}
}
// Transaction error callback
function errorCB(err)
{
console.log("Error processing SQL: "+err.code);
}
Inside your code for save call
db.transaction(populateDB, errorCB, successCB)
The function will return to
function populateDB(tx) {
var rr=escape(JSON.stringify(onedata));//here onedata is data you want to save I use json data here.
tx.executeSql('CREATE TABLE IF NOT EXISTS LeadInfo (data)');
tx.executeSql('INSERT INTO LeadInfo (data) VALUES ("'+ rr +'")');
alert("Insert")
}
function errorCB(tx, err) {
//alert("Error processing SQL Insert: "+err);
}
function successCB() {
// alert("success!");
}
For retrieval you can use following:
function queryDB(tx) {
tx.executeSql('SELECT * FROM LeadInfo', [], querySuccess, errorCB);
}
function querySuccess(tx, results) {
var tablereport="";
if (results != null && results.rows != null) {
for (var i = 0; i < results.rows.length; i++) {
var row =unescape(results.rows.item(i).data);
var obj = JSON.parse(row);
tablereport+='<a href="#"><span style="font-size:18px; font-weight:400; padding:10px 0px 10px 0px;">'+JSON.stringify(obj.lead_name)+'</span><span style="padding: 10px 16px;width: 100px;float: right;margin-top: -33px;margin-right: -80px;font-size:14px"></span><br>';
tablereport+='</li>';
tablereport+='</li>';
}
}
}
function errorCB(err) {
alert("Error processing SQL Retrive: "+err.code);
}
Related
I am new in android PhoneGap.
<script type="text/javascript" charset="utf-8" src="js/cordova.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var db = window.openDatabase("raddyx", "1.0", "Cordova Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}
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")');
}
function errorCB(tx, err) {
alert("Error processing SQL: "+err);
}
function successCB() {
alert("success!");
}
</script>
I am using above sample code. My database name raddyx. I am unable to create database. Can you please say me how to create raddyx database in PhoneGap?
Edit - When i run it in my mobile it says Unfortunately, APP_NAME_HERE has stopped. If i remove my connection code it works fine.
You can create a database with a function like:
function queryDB() {
var db = window.openDatabase("Database", "1.0", "Cordova login", 300000);
db.transaction(inputDb, errorCB);
}
After that, you call the function inputDb which looks like:
function inputeDb(db2) {
db2.executeSql('DROP TABLE IF EXISTS login');
db2.executeSql('CREATE TABLE IF NOT EXISTS login (id_Login INTEGER PRIMARY KEY AUTOINCREMENT, UserName VARCHAR(150) NULL, UserPassword VARCHAR(100) NULL, UserHash VARCHAR(50) NULL)');
db2.executeSql('INSERT INTO login (UserName, UserPassword) VALUES ("'+uname1+'", "'+upass1+'")');
db2.executeSql('DROP TABLE IF EXISTS MDataT');
db2.executeSql('CREATE TABLE IF NOT EXISTS MDataT (id_MData INTEGER PRIMARY KEY, MData INTEGER)');
db2.executeSql('INSERT INTO MDataT (id_MData, MData) VALUES ("1", "'+MData+'")');
//alert("Username and Password - Set in DB");
location.href="serverLogin.html";
}
I created an android app using html5 and phonegap and
I have a problem in inserting data into database..
this is my code
document.addEventListener("deviceready", onDeviceReady(), false);
var db;
function onDeviceReady(){
db = window.openDatabase("Libsys", "2.0", "LibraryDB", 200000); //will create database Dummy_DB or open it
db.transaction(populateDB, errorCB, successCB);
}
function populateDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS Borrowinfo(id INTEGER PRIMARY KEY AUTOINCREMENT, IDno TEXT NOT NULL, Name TEXT NOT NULL, course TEXT NOT NULL, author TEXT NOT NULL, title TEXT NOT NULL, date_start TEXT NOT NULL, date_return TEXT NOT NULL)');
}
function queryDB(tx){
tx.executeSql('SELECT * FROM Borrowinfo', [], querySuccess, errorCB);
}
function querySuccess(tx,results){
var len = results.rows.length;
for (var i = 0; i < len; i++) {
var row = results.rows.item(i);
$("#Lists").append("<li><a href='#'>"+row['Name']+" "+row['course']+"</a></li>");
}
$("#Lists").listview("refresh");
}
function SaveContacts(idno,fullname,course,author,title,dstart,dreturn){
//alert(""+idno+" "+fullname+"");
db.transaction(function(tx){
var idno = document.getElementById("idno").value;
var fullname = document.getElementById("names").value;
var course = document.getElementById("course").value;
var author = document.getElementById("author").value;
var title = document.getElementById("title").value;
var dstart = document.getElementById("dstart").value;
var dreturn = document.getElementById("dreturn").value;
tx.executeSql('INSERT INTO Borrowinfo(IDno,name,course,author,title,date_start,date_return) VALUES (?,?,?,?,?,?,?)', [idno,fullname,course,author,title,dstart,dreturn], querySuccess);
alert("Record Save!");
});
}
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
function successCB() {
db.transaction(queryDB,errorCB);
}
im having an error in the function querySuccess.. the error message is (undefined is not a function querySuccess)
Please, correct me and also help me to fixed the error...
thank you..
I'm using PhoneGap and a SQLite Database.
I try something like this:
I have a function useSavedThing():
function useSavedThing() {
alert("BEFORE getSavedThing()");
getSavedThing();
alert("AFTER getSavedThing()");
}
and a function getSavedThing():
function getSavedThing(){
alert("ONE");
var db = window.openDatabase("Database", "1.0", "Database", 200000);
db.transaction(populateDB, errorCB, successCB);
alert("TWO");
function populateDB(tx) {
alert("THREE");
}
function errorCB(tx, err) {
alert("Error processing SQL: " + err);
}
function successCB() {
alert("FOUR");
db.transaction(getData);
}
function getData(tx) {
alert("FIVE");
tx.executeSql('SELECT * FROM SETTINGS', [], getIt, errorCB);
}
function getIt(tx, results) {
alert("SIX");
var savedthing = results.rows.item(0).data;
}
}
The problem is that when the function getSavedThing() is called, only the first two alerts (alert("ONE"), alert("TWO)) issued but then the alert ("AFTER getSavedThing ()") called.
But I want that all expenses alert ("ONE"), alert ("TWO"), alert ("THREE") alert ("FOUR") alert ("FIVE"), alert ("SIX"), issued before the alert("AFTER getSavedThing()"); appers.
The order fo the alerts should be:
alert("BEFORE getSavedThing()");
alert("ONE");
alert("TWO");
alert("THREE");
alert("FOUR");
alert("FIVE");
alert("SIX");
alert("BEFORE getSavedThing()");
Can someone help me?
Database operations are performed asynchronously. If you want alert("AFTER getSavedThing()") to be executed after the last database operation it needs to be called from the callback function getIt();
function useSavedThing() {
alert("BEFORE getSavedThing()");
var afterGet = function(){
alert("AFTER getSavedThing()");
}
getSavedThing( afterGet ); /*pass the callback function to getSavedThing*/
}
function getSavedThing( callback ){
alert("ONE");
var db = window.openDatabase("Database", "1.0", "Database", 200000);
db.transaction(populateDB, errorCB, successCB);
alert("TWO");
function populateDB(tx) {
alert("THREE");
}
function errorCB(tx, err) {
alert("Error processing SQL: " + err);
}
function successCB() {
alert("FOUR");
db.transaction(getData);
}
function getData(tx) {
alert("FIVE");
tx.executeSql('SELECT * FROM SETTINGS', [], getIt, errorCB);
}
function getIt(tx, results) {
alert("SIX");
var savedthing = results.rows.item(0).data;
callback.call(); /*execute the callback function*/
}
}
You can use this framework for data access in PhoneGap, you will find it quite easy to use:
var db = new MyDB();
//query all users
var users = db.Users.toArrary(callback);
I am trying to set up database to store user image and name. I have put the code up on jsfiddle http://jsfiddle.net/Inkers/dZJnG/. When I run the code on my device I get a number of errors. Code here too:
HTML
<body onload="onDeviceReady()">
<h3>Enter name and picture</h3>
<div id= "userProfile">
<button onclick="takePhoto();">Capture Photo</button> <br>
<img style="display:none;width:100px;height:100px;" id="smallImage" src="" />
<p></p>
<input id="userName" type="text" placeholder="name">
<input id="saveProfile" type="button" value="Save" onClick="insertEntry();""location.href='Createtask.html'"> <br>
<input id="allUsers" type="button" value="All users" onClick="queryDB();"> <br>
</div>
JS
function init(){
document.addEventListener("deviceready", onDeviceReady, false);
}
var pictureSource; // picture source
var destinationType;
function onDeviceReady() {
var db = window.openDatabase("database", "1.0", "Profiles", 5000);
if(db) {
console.log('The database is working');
alert('The database is working');
db.transaction(createTable, insertEntry, errorCB, successCB); // only do stuff if db exists
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
else{
console.log('There is a problem');
}
}
function takePhoto(){
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50 });
}
function onPhotoDataSuccess(imageData) {
console.log(imageData);
// Get image handle
var smallImage = document.getElementById('smallImage');
// Unhide image elements
smallImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
smallImage.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
function createTable(tx) {
var sqlStr =('CREATE TABLE IF NONE EXISTS USERS(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, image BLOB)');
tx.executeSql(sqlStr,[],successCB, errorCB);
console.log("Users table created");
}
function insertEntry(tx){
var tmpName = document.getElementById("userName").value;
var tmpImage = document.getElementById("smallImage").src;
var sqlStr=('INSERT INTO USERS (name, image) VALUES (?,?)');
tx.executeSql = (sqlStr, [tmpName, tmpImage], onSqlSuccess, errorCB);
alert('record entered');
}
// Query the success callback
function onSqlSuccess(tx, res){
var len = results.rows.length;
console.log("USERS table: " + len + " rows found.");
for (var i=0; i<len; i++){
console.log("Row = " + i + " ID = " + results.rows.item(i).id + " Data = " + results.rows.item(i).data);
}
}
// Query the database
//
function queryDB() {
var sqlStr = ('SELECT * FROM USERS; ORDER BY id ASC');
database.transaction(function (tx){
tx.executeSql(sqlStr,[],onSqlSuccess, errorCB);
})
}
// Transaction error callback
//
function errorCB(err) {
console.log("Error processing SQL: "+err.code);
}
// Transaction success callback
//
function successCB() {
console.log('');
}
Im trying out and copied code from here:
http://luthfihariz.wordpress.com/2011/10/23/android-sqlite-phonegap-jquerymobile/
To succeed with a sample I'm working on just to learn this.
I have a link to my complete index.html on pastebin.
Please, correct me and also help me finding this errror.
Link to Pastebin here
I didn't have a lot of time, and it's soon xmas :) But.. :) I did write you a working example with your code as a starter.
Using Cordova version 2.2.0
Using PhoneGap to compile
I did test it on an android device
I did change some things here and there, but I used the code frome here as a reference.
document.addEventListener("deviceready", onDeviceReady, false);
var db = "";
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS SoccerPlayer');
tx.executeSql('CREATE TABLE IF NOT EXISTS SoccerPlayer (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 queryDB(tx) {
tx.executeSql('SELECT * FROM SoccerPlayer', [], querySuccess, errorCB);
}
function querySuccess(tx,result){
var playerlist = document.getElementById("SoccerPlayerList");
var players = "";
alert("The show is on");
var len = result.rows.length;
for (var i=0; i<len; i++){
alert(result.rows.item(i).Name + result.rows.item(i).Club);
players = players + '<li><p class="record">'+result.rows.item(i).Name+'</p><p class="small">Club '+result.rows.item(i).Club+'</p></li>';
}
playerlist.innerHTML = players;
$("#SoccerPlayerList").listview("refresh");
}
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
function successCB() {
db.transaction(queryDB, errorCB);
}
function onDeviceReady() {
db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}