I have developed a multi-platform app using AngularJS, JavaScript, Phonegap/Cordova, Monaca, and Onsen UI.
In order to enable offline usage of the app, I have integrated an SQLite Database to store various data. After conducting some basic tests, I confirmed that this functionality is working correctly.
My current challenge involves creating all 28 required tables within my app's initial view function onDeviceReady(). To achieve this, I am iterating through an array of objects and executing the SQLite CREATE statement for each table.
Defining table values
// Form values
var formValues = [{
tablename: "table_1",
id: "id_1",
desc: "desc_1",
dataType: "TEXT"
}, {
tablename: "table_2",
id: "id_2",
desc: "desc_2",
dataType: "TEXT"
}, {
...
...
...
...
}, {
tablename: "table_28",
id: "id_28",
desc: "desc_28",
dataType: "TEXT"
}];
Creating the tables
function onDeviceReady() {
for (var i = 0; i < formValues.length; i++) {
var createFormValues = 'CREATE TABLE IF NOT EXISTS ' + formValues[i].tablename + ' (' + formValues[i].id + ' INTEGER, ' + formValues[i].desc + ' ' + formValues[i].dataType + ')';
alert("SQL: " + createFormValues +
"\n\nForm: " + formValues +
"\nName: " + formValues[i].tablename +
"\nID: " + formValues[i].id +
"\nDesc: " + formValues[i].desc +
"\nType: " + formValues[i].dataType);
db.transaction(function (tx) { tx.executeSql(createFormValues); });
}
};
After running the code above, I found that only the last table was created when querying the tables post loop execution.
To address this issue, I resorted to calling individual functions for each table creation, which proved to be less efficient but successful in generating all tables.
Calling a function
createFormTables("table_1", "id_1", "desc_1", "TEXT");
createFormTables("table_2", "id_2", "desc_2", "TEXT");
createFormTables("...", "...", "...", "...");
createFormTables("table_28", "id_28", "desc_28", "TEXT");
Executing the function
createFormTables: function (tableName, id, description, dataType) {
var sql = 'CREATE TABLE IF NOT EXISTS ' + tableName + ' (' + id + ' INTEGER, ' + description + ' ' + dataType + ')';
alert("Create Form Field SQL: " + sql);
db.transaction(function (tx) { tx.executeSql(sql); });
},
The asynchronous nature of SQLite statements seems to be causing the discrepancy between the two approaches. I am unsure why the first method fails to create all tables while the second one succeeds. How can I ensure that the tables are created using the initial approach without resorting to delays?