Hi,
Thanks for visiting.
This content has been moved to new domain.
https://developerswing.blogspot.com/
Pease use the below URL to view the content:
Phone Book App using SQLite, PhoneGap, Android and Eclipse
Thanks
Today in this example I will show you how to use SQLite database with PhoneGap and jQuery Mobile Architecture. From this example you will get to know how to override the default Android Back Button behaviour and also how to use both tap and taphold event.
So lets begin, I have given the name of the application is ‘MyContacts’. So first create an android project using phonegap and eclipse. If you are unable to do this please go through Hello World! with PhoneGap, Android and Eclipse tutorial.
Now create three divs/pages in your index.html page. And also make sure whatever ID’s you are using to select the DOM element or to bind some events with that element has to be unique. The moment you introduce a duplicate id, you have an invalid document on your hands.
<!-- Index Page Start --> <div id="index"> <div> <a href="#" class="refresh" title="Refresh">Refresh</a> <h1>My Contacts</h1> <a href="#" class="addNew" title="Add New">Add</a></div> <div> <ul id="userList"></ul> </div> <div id="actionList-popup"> <ul id="actionList" style="border:1px solid blue;width:15em;"></ul> </div> </div> <!-- Index Page End --> <!-- Data Display Page Start --> <div id="displayDataPage"> <div> <a href="#" class="back" title="Back">Back</a> <h1 id="nameHeader"></h1> <a href="#" class="addNew" title="Add New">Add</a></div> <div> <ul id="dataList"> <li>Name : <span id="dataName"></span></li> <li>Nick Name : <span id="dataNickName"></span></li> <li>Mobile Phone Number : <span id="dataMobilePhoneNumber"></span></li> <li id="mpnCallSMS"></li> <li>Work Phone Number : <span id="dataWorkPhoneNumber"></span></li> <li id="wpnCallSMS"></li> <li>Email Id : <span id="dataEmailId"></span></li> <li>Website : <span id="dataWebsite"></span></li> <li>Happy Birth Day : <span id="dataHappyBirthDay"></span></li> </ul> </div> </div> <!-- Data Display Page End --> <!-- Form Page Start --> <div id="addNewPage"> <div> <a href="#" class="back" title="Back">Back</a> <h1 id="addNewPageHeader"></h1> <a href="#" id="save" title="Save">Save</a></div> <div> <div class='error'></div> <div> Name: </div> <div> Nick Name: </div> <div> Mobile Number: </div> <div> Work Phone Number: </div> <div> Email Id: </div> <div> Website: </div> <div> Happy Birth Day: </div> </div> </div> <!-- Form Page End -->Now add the following JavaScript code inside a script tag in index.html page.
$(document).ready(function(){ document.addEventListener("deviceready", onDeviceReady, false); var db = window.openDatabase("Database", "1.0", "MyContactsDB", 200000); function onDeviceReady(){ //Populate the databse db.transaction(populateDB, errorCB, successCB); //Override the back button functionality document.addEventListener('backbutton', onBack, false); } function onBack(){ //If the current page is index page then exit other wise navigate to index page if($.mobile.activePage.is('#index')){ navigator.app.exitApp(); } else{ db.transaction(queryDB, errorCB); } } function populateDB(tx){ //Create the table //tx.executeSql('DROP TABLE IF EXISTS MyContacts'); tx.executeSql('CREATE TABLE IF NOT EXISTS MyContacts (id INTEGER PRIMARY KEY AUTOINCREMENT, \ name TEXT NOT NULL, nickName TEXT, mobilePhoneNumber INT, \ workPhoneNumber INT, emailId TEXT, website TEXT, happyBirthDay TEXT)\ '); tx.executeSql('SELECT id, name, nickName FROM MyContacts ORDER BY name', [], querySuccess, errorCB); } function successCB(){ db.transaction(queryDB, errorCB); } function queryDB(tx){ tx.executeSql('SELECT id, name, nickName FROM MyContacts ORDER BY name', [], querySuccess, errorCB); } function querySuccess(tx, results){ $.mobile.showPageLoadingMsg(true); var len = results.rows.length; $("#userList").html(''); for (var i=0; i<len; i++){ var row= results.rows.item(i); var htmlData = ' <li><a href="#"> <h2>'+row["name"]+'</h2> '+row["nickName"]+' </a></li> '; $("#userList").append(htmlData).listview('refresh'); } $.mobile.changePage($("#index"), { transition : "slide"}); $.mobile.hidePageLoadingMsg(); } function errorCB(err){ } $("#addNewPage .error").html('').hide(); $(".addNew").bind ("click", function (event){ $("#addNewPage .error").html('').hide(); $.mobile.changePage ($("#addNewPage"), { transition : "slide", reverse : true }); $("#addNewPageHeader").html("Add New"); }); $("#save").bind ("click", function (event){ var name = $.trim($("#name").val()).replace(/[^A-Za-z0-9 ]/g, ''); var nickName = $.trim($("#nickName").val()).replace(/[^A-Za-z0-9 @]/g, ''); var mobilePhoneNumber = $.trim($("#mobilePhoneNumber").val()).replace(/[^0-9-]/g, ''); var workPhoneNumber = $.trim($("#workPhoneNumber").val()).replace(/[^0-9-]/g, ''); var emailId = $.trim($("#emailId").val()); var website = $.trim($("#website").val()); var happyBirthDay = $.trim($("#happyBirthDay").val()); console.log(name+' '+nickName+' '+mobilePhoneNumber+' '+workPhoneNumber+' '+emailId+' '+website+' '+happyBirthDay); if (name == ''){ $("#addNewPage .error").html('Please enter name.').show(); } else{ resetForm(); var id = $("#id").val(); $("#id").val(''); if (id == ''){ //Save db.transaction(function (tx){ tx.executeSql("INSERT INTO MyContacts (name, nickName, mobilePhoneNumber, workPhoneNumber, emailId, website, happyBirthDay) VALUES (?, ?, ?, ?, ?, ?, ?)",[name, nickName, mobilePhoneNumber, workPhoneNumber, emailId, website, happyBirthDay], queryDB, errorCB); }); } else{ //Update db.transaction(function (tx){ tx.executeSql("UPDATE MyContacts SET name=?, nickName=?, mobilePhoneNumber=?, workPhoneNumber=?, emailId=?, website=?, happyBirthDay=? WHERE id=? ",[name, nickName, mobilePhoneNumber, workPhoneNumber, emailId, website, happyBirthDay, id], queryDB, errorCB); }); } db.transaction(queryDB, errorCB); } }); $(".refresh").bind("click", function (event){ db.transaction(queryDB, errorCB); }); $(".back").bind("click", function (event){ resetForm(); db.transaction(queryDB, errorCB); }); function resetForm(){ $("#addNewPage .error").html('').hide(); $("#addNewPage #name").val(''); $("#addNewPage #nickName").val(''); $("#addNewPage #mobilePhoneNumber").val(''); $("#addNewPage #workPhoneNumber").val(''); $("#addNewPage #emailId").val(''); $("#addNewPage #website").val(''); $("#addNewPage #happyBirthDay").val(''); $("#addNewPage #addNewPageHeader").html(''); } $("#index [data-role='content'] ul").on('tap taphold', 'li', function (event){ event.preventDefault(); event.stopImmediatePropagation(); var liId = this.id; if (event.type === 'taphold'){ navigator.notification.vibrate(30); var $popup = $('#actionList-popup'); $("#actionList").html(''); $("#actionList").append(' <li id="edit&'+liId+'">Edit</li> ').listview('refresh'); $("#actionList").append(' <li id="delete&'+liId+'">Delete</li> ').listview('refresh'); $popup.popup(); $popup.popup('open'); $("#tapHoldCheck").val('true'); } else if (event.type === 'tap'){ if ($("#tapHoldCheck").val() == ''){ //If the value of the text box is blank then only tap will work db.transaction(function (tx){ tx.executeSql("SELECT name, nickName, mobilePhoneNumber, workPhoneNumber, emailId, website, happyBirthDay FROM MyContacts WHERE id=?;", [liId], function (tx, results){ var row = results.rows.item(0); $.mobile.showPageLoadingMsg(true); $.mobile.changePage($("#displayDataPage"), { transition : "slide"}); $("#nameHeader").html(row['name']); $("#dataName").html(row['name']); $("#dataNickName").html(row['nickName']); $("#dataMobilePhoneNumber").html(row['mobilePhoneNumber']); if(row['mobilePhoneNumber'] != ''){ $("#mpnCallSMS").html( ' <div class="ui-grid-a">' + ' <div class="ui-block-a">'+ '<a href="tel:'+row['mobilePhoneNumber']+'">Call</a>' + '</div> ' + ' <div class="ui-block-b">' + '<a href="'+row['mobilePhoneNumber']+'">SMS</a>' + '</div> ' + '</div> ' ); } else{ $("#mpnCallSMS").html(''); } $("#dataWorkPhoneNumber").html(row['workPhoneNumber']); if(row['workPhoneNumber'] !='' ){ $("#wpnCallSMS").html( ' <div class="ui-grid-a">' + ' <div class="ui-block-a">'+ '<a href="tel:'+row['workPhoneNumber']+'">Call</a>' + '</div> ' + ' <div class="ui-block-b">' + '<a href="'+row['workPhoneNumber']+'">SMS</a>' + '</div> ' + '</div> ' ); } else{ $("#wpnCallSMS").html(''); } $("#dataEmailId").html('<a href="mailto:'+row['emailId']+'">'+row['emailId']+'</a>'); $("#dataWebsite").html('<a href="'+row['website']+'">'+row['website']+'</a>'); $("#dataHappyBirthDay").html(row['happyBirthDay']); $('#dataList').trigger('create'); $('#dataList').listview('refresh'); $.mobile.hidePageLoadingMsg(); }); }); } } }); //Change the hidden field value when the popup is closed $('#actionList-popup').bind({ popupafterclose: function(event, ui){ $("#tapHoldCheck").val(''); } }); $("#index [data-role='popup'] ul").on('click', 'li', function (event){ var action_liId = this.id.split('&'); var action = action_liId[0]; var id = action_liId[1]; if (action == 'edit'){ db.transaction(function (tx){ tx.executeSql("SELECT name, nickName, mobilePhoneNumber, workPhoneNumber, emailId, website, happyBirthDay FROM MyContacts WHERE id=?;", [id], function (tx, results){ var row = results.rows.item(0); $("#name").val(row['name']); $("#nickName").val(row['nickName']); $("#mobilePhoneNumber").val(row['mobilePhoneNumber']); $("#workPhoneNumber").val(row['workPhoneNumber']); $("#emailId").val(row['emailId']); $("#website").val(row['website']); $("#happyBirthDay").val(row['happyBirthDay']); $("#id").val(id); $("#addNewPageHeader").html('Edit'); $.mobile.changePage ($("#addNewPage"), { transition : "slide", reverse : true }); }); }); } if (action == 'delete'){ navigator.notification.confirm( 'Are you sure?', function(buttonIndex){onConfirm(buttonIndex, id);}, 'Delete Contact', 'Ok, Cancel' ); } }); function onConfirm(buttonIndex, id){ if (buttonIndex === 1){ //Delete db.transaction(function (tx){ tx.executeSql("DELETE FROM MyContacts WHERE id=?", [id], queryDB, errorCB); }); } if (buttonIndex === 2){ $.mobile.changePage($("#index"), { transition : "slide"}); } } });While at the time of developing this application I have faced the problem of tap and taphold event.
The problem is that the tap event is fired after the taphold event once I lift my finger. So to resolve this problem I have used a function popupafterclose and a hidden filed (id of the hidden field is ‘tapHoldCheck’). The logic behind that is that, by default the value of the hidden field is blank, so when the taphold event is fired I am putting some value on the hidden field and also at the time of closing the popup window again the value of hidden field becomes blank.And finally your index.html page will look like following.
My Contacts .error{ font-size: 0.8em; border: 1px solid; margin: 10px 0px; padding:15px 10px 15px 8px; text-align:center; color: #D8000C; background-color: #FFBABA; } $(document).ready(function(){ document.addEventListener("deviceready", onDeviceReady, false); var db = window.openDatabase("Database", "1.0", "MyContactsDB", 200000); function onDeviceReady(){ //Populate the databse db.transaction(populateDB, errorCB, successCB); //Override the back button functionality document.addEventListener('backbutton', onBack, false); } function onBack(){ //If the current page is index page then exit other wise navigate to index page if($.mobile.activePage.is('#index')){ navigator.app.exitApp(); } else{ db.transaction(queryDB, errorCB); } } function populateDB(tx){ //Create the table //tx.executeSql('DROP TABLE IF EXISTS MyContacts'); tx.executeSql('CREATE TABLE IF NOT EXISTS MyContacts (id INTEGER PRIMARY KEY AUTOINCREMENT, \ name TEXT NOT NULL, nickName TEXT, mobilePhoneNumber INT, \ workPhoneNumber INT, emailId TEXT, website TEXT, happyBirthDay TEXT)\ '); tx.executeSql('SELECT id, name, nickName FROM MyContacts ORDER BY name', [], querySuccess, errorCB); } function successCB(){ db.transaction(queryDB, errorCB); } function queryDB(tx){ tx.executeSql('SELECT id, name, nickName FROM MyContacts ORDER BY name', [], querySuccess, errorCB); } function querySuccess(tx, results){ $.mobile.showPageLoadingMsg(true); var len = results.rows.length; $("#userList").html(''); for (var i=0; i<len; i++){ var row= results.rows.item(i); var htmlData = ' <li><a href="#"> <h2>'+row["name"]+'</h2> '+row["nickName"]+' </a></li> '; $("#userList").append(htmlData).listview('refresh'); } $.mobile.changePage($("#index"), { transition : "slide"}); $.mobile.hidePageLoadingMsg(); } function errorCB(err){ } $("#addNewPage .error").html('').hide(); $(".addNew").bind ("click", function (event){ $("#addNewPage .error").html('').hide(); $.mobile.changePage ($("#addNewPage"), { transition : "slide", reverse : true }); $("#addNewPageHeader").html("Add New"); }); $("#save").bind ("click", function (event){ var name = $.trim($("#name").val()).replace(/[^A-Za-z0-9 ]/g, ''); var nickName = $.trim($("#nickName").val()).replace(/[^A-Za-z0-9 @]/g, ''); var mobilePhoneNumber = $.trim($("#mobilePhoneNumber").val()).replace(/[^0-9-]/g, ''); var workPhoneNumber = $.trim($("#workPhoneNumber").val()).replace(/[^0-9-]/g, ''); var emailId = $.trim($("#emailId").val()); var website = $.trim($("#website").val()); var happyBirthDay = $.trim($("#happyBirthDay").val()); console.log(name+' '+nickName+' '+mobilePhoneNumber+' '+workPhoneNumber+' '+emailId+' '+website+' '+happyBirthDay); if (name == ''){ $("#addNewPage .error").html('Please enter name.').show(); } else{ resetForm(); var id = $("#id").val(); $("#id").val(''); if (id == ''){ //Save db.transaction(function (tx){ tx.executeSql("INSERT INTO MyContacts (name, nickName, mobilePhoneNumber, workPhoneNumber, emailId, website, happyBirthDay) VALUES (?, ?, ?, ?, ?, ?, ?)",[name, nickName, mobilePhoneNumber, workPhoneNumber, emailId, website, happyBirthDay], queryDB, errorCB); }); } else{ //Update db.transaction(function (tx){ tx.executeSql("UPDATE MyContacts SET name=?, nickName=?, mobilePhoneNumber=?, workPhoneNumber=?, emailId=?, website=?, happyBirthDay=? WHERE id=? ",[name, nickName, mobilePhoneNumber, workPhoneNumber, emailId, website, happyBirthDay, id], queryDB, errorCB); }); } db.transaction(queryDB, errorCB); } }); $(".refresh").bind("click", function (event){ db.transaction(queryDB, errorCB); }); $(".back").bind("click", function (event){ resetForm(); db.transaction(queryDB, errorCB); }); function resetForm(){ $("#addNewPage .error").html('').hide(); $("#addNewPage #name").val(''); $("#addNewPage #nickName").val(''); $("#addNewPage #mobilePhoneNumber").val(''); $("#addNewPage #workPhoneNumber").val(''); $("#addNewPage #emailId").val(''); $("#addNewPage #website").val(''); $("#addNewPage #happyBirthDay").val(''); $("#addNewPage #addNewPageHeader").html(''); } $("#index [data-role='content'] ul").on('tap taphold', 'li', function (event){ event.preventDefault(); event.stopImmediatePropagation(); var liId = this.id; if (event.type === 'taphold'){ navigator.notification.vibrate(30); var $popup = $('#actionList-popup'); $("#actionList").html(''); $("#actionList").append(' <li id="edit&'+liId+'">Edit</li> ').listview('refresh'); $("#actionList").append(' <li id="delete&'+liId+'">Delete</li> ').listview('refresh'); $popup.popup(); $popup.popup('open'); $("#tapHoldCheck").val('true'); } else if (event.type === 'tap'){ if ($("#tapHoldCheck").val() == ''){ //If the value of the text box is blank then only tap will work db.transaction(function (tx){ tx.executeSql("SELECT name, nickName, mobilePhoneNumber, workPhoneNumber, emailId, website, happyBirthDay FROM MyContacts WHERE id=?;", [liId], function (tx, results){ var row = results.rows.item(0); $.mobile.showPageLoadingMsg(true); $.mobile.changePage($("#displayDataPage"), { transition : "slide"}); $("#nameHeader").html(row['name']); $("#dataName").html(row['name']); $("#dataNickName").html(row['nickName']); $("#dataMobilePhoneNumber").html(row['mobilePhoneNumber']); if(row['mobilePhoneNumber'] != ''){ $("#mpnCallSMS").html( ' <div class="ui-grid-a">' + ' <div class="ui-block-a">'+ '<a href="tel:'+row['mobilePhoneNumber']+'">Call</a>' + '</div> ' + ' <div class="ui-block-b">' + '<a href="'+row['mobilePhoneNumber']+'">SMS</a>' + '</div> ' + '</div> ' ); } else{ $("#mpnCallSMS").html(''); } $("#dataWorkPhoneNumber").html(row['workPhoneNumber']); if(row['workPhoneNumber'] !='' ){ $("#wpnCallSMS").html( ' <div class="ui-grid-a">' + ' <div class="ui-block-a">'+ '<a href="tel:'+row['workPhoneNumber']+'">Call</a>' + '</div> ' + ' <div class="ui-block-b">' + '<a href="'+row['workPhoneNumber']+'">SMS</a>' + '</div> ' + '</div> ' ); } else{ $("#wpnCallSMS").html(''); } $("#dataEmailId").html('<a href="mailto:'+row['emailId']+'">'+row['emailId']+'</a>'); $("#dataWebsite").html('<a href="'+row['website']+'">'+row['website']+'</a>'); $("#dataHappyBirthDay").html(row['happyBirthDay']); $('#dataList').trigger('create'); $('#dataList').listview('refresh'); $.mobile.hidePageLoadingMsg(); }); }); } } }); //Change the hidden field value when the popup is closed $('#actionList-popup').bind({ popupafterclose: function(event, ui){ $("#tapHoldCheck").val(''); } }); $("#index [data-role='popup'] ul").on('click', 'li', function (event){ var action_liId = this.id.split('&'); var action = action_liId[0]; var id = action_liId[1]; if (action == 'edit'){ db.transaction(function (tx){ tx.executeSql("SELECT name, nickName, mobilePhoneNumber, workPhoneNumber, emailId, website, happyBirthDay FROM MyContacts WHERE id=?;", [id], function (tx, results){ var row = results.rows.item(0); $("#name").val(row['name']); $("#nickName").val(row['nickName']); $("#mobilePhoneNumber").val(row['mobilePhoneNumber']); $("#workPhoneNumber").val(row['workPhoneNumber']); $("#emailId").val(row['emailId']); $("#website").val(row['website']); $("#happyBirthDay").val(row['happyBirthDay']); $("#id").val(id); $("#addNewPageHeader").html('Edit'); $.mobile.changePage ($("#addNewPage"), { transition : "slide", reverse : true }); }); }); } if (action == 'delete'){ navigator.notification.confirm( 'Are you sure?', function(buttonIndex){onConfirm(buttonIndex, id);}, 'Delete Contact', 'Ok, Cancel' ); } }); function onConfirm(buttonIndex, id){ if (buttonIndex === 1){ //Delete db.transaction(function (tx){ tx.executeSql("DELETE FROM MyContacts WHERE id=?", [id], queryDB, errorCB); }); } if (buttonIndex === 2){ $.mobile.changePage($("#index"), { transition : "slide"}); } } }); <!-- Index Page Start --> <div id="index"> <div> <a href="#" class="refresh" title="Refresh">Refresh</a> <h1>My Contacts</h1> <a href="#" class="addNew" title="Add New">Add</a></div> <div> <ul id="userList"></ul> </div> <div id="actionList-popup"> <ul id="actionList" style="border:1px solid blue;width:15em;"></ul> </div> </div> <!-- Index Page End --> <!-- Data Display Page Start --> <div id="displayDataPage"> <div> <a href="#" class="back" title="Back">Back</a> <h1 id="nameHeader"></h1> <a href="#" class="addNew" title="Add New">Add</a></div> <div> <ul id="dataList"> <li>Name : <span id="dataName"></span></li> <li>Nick Name : <span id="dataNickName"></span></li> <li>Mobile Phone Number : <span id="dataMobilePhoneNumber"></span></li> <li id="mpnCallSMS"></li> <li>Work Phone Number : <span id="dataWorkPhoneNumber"></span></li> <li id="wpnCallSMS"></li> <li>Email Id : <span id="dataEmailId"></span></li> <li>Website : <span id="dataWebsite"></span></li> <li>Happy Birth Day : <span id="dataHappyBirthDay"></span></li> </ul> </div> </div> <!-- Data Display Page End --> <!-- Form Page Start --> <div id="addNewPage"> <div> <a href="#" class="back" title="Back">Back</a> <h1 id="addNewPageHeader"></h1> <a href="#" id="save" title="Save">Save</a></div> <div> <div class='error'></div> <div> Name: </div> <div> Nick Name: </div> <div> Mobile Number: </div> <div> Work Phone Number: </div> <div> Email Id: </div> <div> Website: </div> <div> Happy Birth Day: </div> </div> </div> <!-- Form Page End -->In your MyContacts/res/xml/config.xml file add the following lines inside the tag.
Add the following activity to your AndroidManifest.xml file. It should be added inside the <application> </application> tag.
And also you need to add the following permision in your AndroidManifest.xml file.
Now run the android project and you will get the following output given below.