When Cordova builds a hybrid APP requiring small-scale storage upon WebView, WebSQL is default and will be an appropriate database to use without any plugins. In the article, we have a database class design for WebSQL, which is efficient to deal with async features of WebSQL APIs.
All codes here are not complicated, so you can easily understand even though you are still students in school. To benefit your learning, we will provide you download link to a zip file thus you can get all source codes for future usage.
Estimated reading time: 8 minutes
EXPLORE THIS ARTICLE
TABLE OF CONTENTS
BONUS
Source Code Download
We have released it under the MIT license, so feel free to use it in your own project or your school homework.
Download Guideline
- Prepare HTTP server such as XAMPP or WAMP in your windows environment.
- Download and unzip into a folder that http server can access.
SECTION 1
Cordova Hybrid APP
Cordova can build a hybrid APP based on codes in HTML, CSS, and JavaScript to be executed on Android or iOS. Then Cordova Plugins help to control vendor-dependent hardware components in devices.
Native APP vs. Hybrid APP
Native APPs are not cross-platform. For example, Android APPs that created by Java and Android SDK can’t execute on iOS, while hybrid APPs are different.
Hybrid APPs are developed just like Web APPs, but they can be converted into Native APPs. The key is the building procedure by using softwares like Cordova. Hybrid APPs take advantages of one-time coding ideally. However, when involving special device or native features, developers still have to separate a certain small portion of codes as independent swapping modules.
Cordova Hybrid Mobile APP
When you complete a website with HTML, CSS, and JavaScript, Cordova can move it to mobile devices by building a hybrid APP, as described in Wikipedia.
Apache Cordova enables software programmers to build hybrid web applications for mobile devices using CSS3, HTML5, and JavaScript, instead of relying on platform-specific APIs like those in Android, iOS, or Windows Phone.
SECTION 2
Cordova WebSQL
WebSQL is a browser default database which Cordova hybrid APP can use. Therefore, without plugins, Cordova let mobile APPs store small-scale data locally. We have applied WebSQL on an APP of How MQTT Plus Cordova GPS APP Track My Family.
Default Databases
Cordova has two default databases, WebSQL and IndexedDB. The provided APIs on default databases are identical to browser databases, so without Plugins, Cordova can store local data in database using JavaScript codes that have been tested in browsers. Thus developers will spend less time on that.
A jQuery Mobile Example
jQuery Mobile overcomes mobile responsive issues in HTML and CSS. First, you should download module files for jQuery Mobile. Here we also download jQuery UI module files for a specific widget used. Note that
- But don’t use CDN in Cordova projects as mentioned in our article.
- The file
cordova.js
must be included for Cordova device events. You don’t have to locate the actual position for it, as Cordova building process will search for that. When tested in browsers, you could result in console log error like 404 (Not Found), but ignore it. - The file
dbclass.js
contains object-oriented WebSQL database class, which make async programming in WebSQL more efficient as we have discussed before.
<link rel="stylesheet" href="css/1.4.5/jquery.mobile.min.css">
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/1.4.5/jquery.mobile.min.js"></script>
<!-- jquery-ui -->
<link rel="stylesheet" href="css/1.12.1/jquery-ui.css">
<script src="js/1.12.1/jquery-ui.js"></script>
<script src="cordova.js"></script>
<script src="js/index.js"></script>
<script src="js/dbclass.js"></script>
Store Scheduled Tasks in APPs
The example store people’s scheduled tasks to local storage in APPs. The date selection is implemented by a widget in jQuery UI, called datepicker
. While a collapsible widget data-role="collapsibleset"
from jQuery Mobile lets you check detailed description for each scheduled task.
<div data-role="page">
<div data-role="header">
<h1>MY SCHEDULE</h1>
</div>
<div data-role="content" class="my-content">
<p>Enter Date: <input type="text" id="datepicker"></p>
<p>Enter Task: <input type="text" id="task"></p>
<p>Enter Description: <textarea type="textarea" id="desc"></textarea></p>
<button type="button" data-icon="gear" data-iconpos="right" data-mini="true" data-inline="true" id="add">Add Task</button>
<p>Task List:</p>
<div data-role="collapsibleset" data-content-theme="a" data-iconpos="right" id="set">
</div>
</div>
<div data-role="footer" data-position="fixed">
<p style="text-align:center;">An Example of Cordova WebSQL</p>
</div>
</div>
When this example starts up, it new a database or open an existing database with an optional callback function Init()
. This function creates a table if not existed, and then launches rows into the collapsible widget by using another callback function displayData()
.
After initialization, you can add a new task by selecting date, typing content of task and description, and clicking add-button to insert a new record into the default database, WebSQL.
$( document ).on( "pagecreate", function() {
$( "#datepicker" ).datepicker();
db = new dbClass("sched_db", "Schedule DB", Init);
$("#add").click(function() {
/* Validate input */
datep = $("#datepicker").val();
if(datep == "") { alert("Invalid Date"); return; }
task = $("#task").val();
if(task == "") { alert("Invalid Task Name"); return; }
desc = $("#desc").val();
if(desc == "") { alert("Empty Content"); return; }
/* Add a task in screen */
addTask(datep, task, desc)
/* Add a task in database */
sql="INSERT INTO sched (datep, task, desc) VALUES (?, ?, ?)";
db.execute(sql, [datep, task, desc]);
});
});
function addTask(datep, task, desc) {
var content = "<div data-role='collapsible' class='task-item'><h3>"
+ datep + " " + task + "</h3><p>" + desc + "</p></div>";
$("#set").append(content).collapsibleset("refresh");
}
function Init() {
sql="CREATE TABLE IF NOT EXISTS sched (datep, task, desc)";
db.execute(sql);
sql="SELECT * FROM sched";
db.execute(sql, [], displayData);
}
function displayData(rows, n, rowsAffected) {
for(var i=0; i<n; i++) {
addTask(rows[i].datep, rows[i].task, rows[i].desc);
}
}
WebSQL Database Class
A database instant is created from the class to perform our operations on tables. The class simplifies programming, and adds informative process in console logs for debugging. Its usage has been described in previous article ……
/* A database class for WebSQL */
class dbClass {
constructor(dbName, dbDisplay="", callback=function(){}) {
this.conn = openDatabase(dbName, '1.0', dbDisplay, 2 * 1024 * 1024); //create or open database
this.conn.transaction(function (tx) { callback(); });
}
execute(sql, arr=[], callback=function(){}) {
console.log(sql);
console.log(arr);
this.conn.transaction(function (tx) {
tx.executeSql(
sql,
arr,
function (tx, stmt) {
console.log(tx);
console.log(stmt);
callback(stmt.rows, stmt.rows.length, stmt.rowsAffected);
},
null
);
});
}
}
SECTION 3
Cordova Building Process
Refer to Cordova setup and building projects, if you are not familiar with it. For this example, we write about Cordova CLI that can create, config, and build a hybrid APP for debug or release versions.
Quick Start
Cordova CLI (command-line interface) lets you start building by this way,
$ cordova create mysched com.easycodeshare.mysched MySched
Where PATH is mysched, ID is com.easycodeshare.mysched, and NAME is MySched. All of them can be found in a config file mysched/config.xml
.
We are going to build APPs. Before that, put your codes in mysched/www
, check if entry point mysched/www/index.html
exists, and keep in mind that no PHP files are allowed, and no CDN reference are available in HTML files.
Build an APP
$ cordova build android
The command line would build a cordova project. Of course, if it is the first time to build, you should add a platform in advance by
$ cordova platform add android
Finally, cordova indicate the long path for resulting APK file like this,
BUILD SUCCESSFUL in 37s
41 actionable tasks: 2 executed, 39 up-to-date
Built the following apk(s):
c:\mysched\platforms\android\app\build\outputs\apk\debug\app-debug.apk
Probably you want a release version, rather than a debug one.
$ cordova build android --release
BUILD SUCCESSFUL in 49s
44 actionable tasks: 44 executed
Built the following apk(s):
c:\mysched\platforms\android\app\build\outputs\apk\release\app-release-unsigned.apk
FINAL
Conclusion
A Cordova hybrid APP using default database such as WebSQL can take advantages of local small-scale storage. In real-world system, server sites always hold mass data, while client ends like mobile APPs usually don’t have storage or just need a few place to keep data.
Thank you for reading, and we have suggested more helpful articles here. If you want to share anything, please feel free to comment below. Good luck and happy coding!
Learning Tips
Let us suggest a excellent way to learn HTML scripts here. Using Google Chrome F12 Inspect or Inspect Element will help you study the codes.
In Google Chrome, there are two ways to inspect a web page using the browser built-in Chrome DevTools:
- Right-click an element on the page or in a blank area, then select Inspect.
- Go to the Chrome menu, then select More Tools > Developer Tools.
Suggested Reading
TRY IT
Quick Experience
That is all for this project, and here is the link that let you experience the program. Please kindly leave your comments for our enhancement.
Try It Yourself
Click here to execute the source code, thus before studying the downloaded codes, you can check whether it is worthy.