openDatabase stuck - javascript

I have a project with Blackberry Web Work, and this is my first time for mobile programming.
I want to create cache database using window.openDatabase
But something is strange, I put alert after to show this database, but it didnot show anything.
I also put alert before and after this function, only show alert before this function
I try to put try catch error, but it still not show error message.
Need your help
Thx
Here is my simple code :
$(document).ready(function() {
try {
if (!window.openDatabase) {
alert('not supported');
} else {
var shortName = 'mydatabase';
var version = '1.0';
var displayName = 'My Important Database';
var maxSize = 65536; // in bytes
alert("prepare to open database");
var db = openDatabase(shortName, version, displayName, maxSize);
alert("open Database");
// You should have a database instance in db.
}
} catch (e) {
// Error handling code goes here.
if (e == 2) {
// Version number mismatch.
alert("Invalid database version.");
} else {
alert("Unknown error " + e + ".");
}
return;
}
alert("Database is: " + db);
});​

Your issue seems to be related to the positioning of your try/catch statements. I rearranged your sample code and it is working:
$(document).ready(function () {
if (!window.openDatabase) {
alert('not supported');
} else {
try {
var shortName = 'mydatabase';
var version = '1.0';
var displayName = 'My Important Database';
var maxSize = 65536; // in bytes
alert("prepare to open database");
var db = openDatabase(shortName, version, displayName, maxSize);
alert("open Database");
// You should have a database instance in db.
} catch (e) {
// Error handling code goes here.
if (e == 2) {
// Version number mismatch.
alert("Invalid database version.");
} else {
alert("Unknown error: " + e + ".");
}
return;
}
alert("Database is: " + db);
}
});
Keep in mind that openDatabase is not supported on all browsers. FireFox and IE will give you the 'not supported' alert, and Chrome and Safari will display the remaining alerts.
Here is the JSFIDDLE link to test the modified code http://jsfiddle.net/sdarya/0pkvLfpv/

Related

onComplete in AjaxUpload getting before server side code hits

I am working on some legacy code which is using Asp.net and ajax where we do one functionality to upload a pdf. To upload file our legacy code uses AjaxUpload, but I observed some weird behavior of AjaxUpload where onComplete event is getting called before actual file got uploaded by server side code because of this though the file got uploaded successfully still user gets an error message on screen saying upload failed.
And here the most weird thins is that same code was working fine till last week.
Code:
initFileUpload: function () {
debugger;
new AjaxUpload('aj-assetfile', {
action: '/Util/FileUploadHandler.ashx?type=asset&signup=False&oldfile=' + assetObj.AssetPath + '&as=' + assetObj.AssetID,
//action: ML.Assets.handlerPath + '?action=uploadfile',
name: 'AccountSignupUploadContent',
onSubmit: function (file, ext) {
ML.Assets.isUploading = true;
ML.Assets.toggleAsfMask(true);
// change button text, when user selects file
$asffile.val('Uploading');
$astfileerror.hide();
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
// Uploding -> Uploading. -> Uploading...
ML.Assets.interval = window.setInterval(function () {
var text = $asffile.val();
if (text.length < 13) {
$asffile.val(text + '.');
} else {
$asffile.val('Uploading');
}
}, 200);
//if url field block is visible
if ($asseturlbkl.is(':visible')) {
$asfurl.val(''); //reset values of url
$asfurl.removeClass('requiref error'); //remove require field class
$asfurlerror.hide(); //hide errors
}
},
onComplete: function (file, responseJSON) {
debugger;
ML.Assets.toggleAsfMask(false);
ML.Assets.isUploading = false;
window.clearInterval(ML.Assets.interval);
this.enable();
var success = false;
var responseMsg = '';
try {
var response = JSON.parse(responseJSON);
if (response.status == 'success') { //(response.getElementsByTagName('status')[0].textContent == 'success') {
success = true;
} else {
success = false;
responseMsg = ': ' + response.message;
}
} catch (e) {
success = false;
}
if (success) {
assetObj.AssetMimeType = response.mimetype;
$asffile.val(response.path);
$asffile.valid(); //clear errors
ML.Assets.madeChanges();
if (ML.Assets.saveAfterUpload) { //if user submitted form while uploading
ML.Assets.saveAsset(); //run the save callback
}
} else { //error
assetObj.AssetMimeType = "";
$asffile.val('');
$astfileerror.show().text('Upload failed' + responseMsg);
//if url field block is visible and type is not free offer.
if ($asseturlbkl.is(':visible') && this.type !== undefined && assetObj.AssetType != this.type.FREEOFFER) {
$asfurl.addClass('requiref'); //remove require field class
}
ML.Assets.hideLoader();
}
}
});
}
I was facing the same issue but I fixed it with some minor change in plugin.
When “iframeSrc” is set to “javascript:false” on https or http pages, Chrome now seems to cancel the request. Changing this to “about:blank” seems to resolve the issue.
Old Code:
var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
New Code with chagnes:
var iframe = toElement('<iframe src="about:blank;" name="' + id + '" />');
After changing the code it's working fine. I hope it will work for you as well. :)
Reference (For more details): https://www.infomazeelite.com/ajax-file-upload-is-not-working-in-the-latest-chrome-version-83-0-4103-61-official-build-64-bit/

titanium iOS app for adhoc distribution stuck on splash screen

I'm running a titanium iOS application, it works as expected on the simulator and also on the device when I run it from appcelerator studio, however when I package the app for adhoc distribution and install it on my iPhone device via iTunes it just gets stuck on the splash screen.
Also I can not debug because it is adhoc distribution. The only thing I noticed using alerts is that it runs through alloy.js but never gets to index.js
Any help would be appreciated.
edit: these are my index and alloy files.
index.js
// Arguments passed into this controller can be accessed via the `$.args` object directly or:
var args = $.args;
var webServices = require("webService");
var TAG = "[loginActivity.js] : ";
var fb = Alloy.Globals.Facebook;
var win = $.window;
var core = require("core");
var network = require("NETWORK");
sessionStatus = Ti.App.Properties.getBool('session');
console.log("session estatus "+sessionStatus);
if(!sessionStatus)
Ti.App.Properties.setBool('session', false);
sessionStatus = Ti.App.Properties.getBool('session');
console.log("session estatus "+sessionStatus);
Ti.App.session=sessionStatus;
manageLogin();
Ti.App.addEventListener('resumed',function(e){
//check if login is still valid
console.log("hola");
manageLogin(); //I just reuse my login logic on resume
});
function manageLogin(){
if(Ti.App.session==false){
// require("core").openLogin;
console.log("abro login");
openLogin();
}else{
console.log("abro main");
Ti.App.User_id= Ti.App.Properties.getInt('User_id');
//Ti.App.profIm =Ti.App.Properties.getObject('image');
require("core").openMainActivity();
}
}
function openLogin(){
console.log("First attempt to use geolocation services.");
var hasLocationPermissions = Ti.Geolocation.hasLocationPermissions(Ti.Geolocation.AUTHORIZATION_WHEN_IN_USE);
Ti.API.info('Ti.Geolocation.hasLocationPermissions', hasLocationPermissions);
if (hasLocationPermissions) {
console.log("GPS permissions granted.");
open();
} else {
console.log("Second attempt");
Ti.Geolocation.requestLocationPermissions(Ti.Geolocation.AUTHORIZATION_WHEN_IN_USE, function(e) {
if (e.success) {
// $.index.open();
open();
} else {
console.log("Something happened during second attempt");
if (OS_ANDROID) {
//alert('You denied permission for now, forever or the dialog did not show at all because you denied it forever earlier.');
var activity = Titanium.Android.currentActivity;
activity.finish();
open();
}
// We already check AUTHORIZATION_DENIED earlier so we can be sure it was denied now and not before
Ti.UI.createAlertDialog({
title : 'You denied permission.',
// We also end up here if the NSLocationAlwaysUsageDescription is missing from tiapp.xml in which case e.error will say so
message : e.error
}).show();
}
});
}
}
function open(e) {
var nextWin = core.createWindow({
controllerName : "loginActivity"
});
if (OS_ANDROID) {
nextWin.fbProxy = Alloy.Globals.Facebook.createActivityWorker({lifecycleContainer: nextWin});
}
nextWin.addEventListener("postlayout", function checkGPS(e){
nextWin.removeEventListener("postlayout", checkGPS);
if(Ti.Geolocation.getLocationServicesEnabled() === false) {
if(OS_ANDROID){
var alertDlg = Titanium.UI.createAlertDialog({
title:'GPS apagado',
message:'El GPS está apagado. Enciéndelo en ajustes.',
buttonNames: ['No encender el gps', 'Abrir ajustes']
});
alertDlg.cancel = 0;
alertDlg.addEventListener('click', function(e){
if(!e.cancel) {
//open up the settings page
var settingsIntent = Titanium.Android.createIntent({
action: 'android.settings.LOCATION_SOURCE_SETTINGS'
});
Titanium.Android.currentActivity.startActivity(settingsIntent);
}
});
alertDlg.show();
}
else {
alert("No se detecta tu ubicación, te recomendamos encender el GPS antes de iniciar la aplicación.");
}
}
});
nextWin.open();
}
and alloy.js
(function(){
var ACS = require('ti.cloud'),
env = Ti.App.deployType.toLowerCase() === 'production' ? 'production' : 'development',
username = Ti.App.Properties.getString('acs-username-'+env),
password = Ti.App.Properties.getString('acs-password-'+env);
// if not configured, just return
if (!env || !username || !password) { return; }
/**
* Appcelerator Cloud (ACS) Admin User Login Logic
*
* fires login.success with the user as argument on success
* fires login.failed with the result as argument on error
*/
ACS.Users.login({
login:username,
password:password,
}, function(result){
Ti.API.info("Yes, logged in.");
if (env==='development') {
Ti.API.info('ACS Login Results for environment `'+env+'`:');
Ti.API.info(result);
}
if (result && result.success && result.users && result.users.length){
Ti.App.fireEvent('login.success',result.users[0],env);
} else {
Ti.App.fireEvent('login.failed',result,env);
}
});
})();
Alloy.Globals.Facebook = require('facebook');
var T = function (name) {
return require('T/' + name);
};
T('trimethyl');
var Notifications = T('notifications');
Notifications.onReceived = function(e) {
console.log("onreceived "+JSON.stringify(e));
alert(e.data);
};
Notifications.subscribe();
console.log("token "+Notifications.getRemoteDeviceUUID());
For future references.
I had to test step by step, block by block and line by line using a single alert at a time to find out what part of the code was causing the application to crash.
I did find out that 2 separate files were calling each other like require("file2") in file 1 and require("file1") in file 2. Although I don't know why this problem/bug/whatever happened only in distribution ad-hoc mode and not when running the app directly from the computer.

Twilio chat events memberUpdated, and userInfoUpdated never fired

i'm looking on what cases are these events is firing, i have implement it on these code
jQuery(document).ready(function() {
var chatChannel;
var chatClient;
var username;
var $input = $('#chat-input');
$.post("/tokens", function(data) {
username = data.username;
chatClient = new Twilio.Chat.Client(data.token);
chatClient.getSubscribedChannels().then(createOrJoinGeneralChannel);
});
function createOrJoinGeneralChannel() {
// Get the general chat channel, which is where all the messages are
// sent in this simple application
// print('Attempting to join "general" chat channel...');
var promise = chatClient.getChannelByUniqueName("#{params[:chat_channel]}");
promise.then(function(channel) {
chatChannel = channel;
console.log("#{params[:chat_channel]} is exist");
console.log(chatChannel);
setupChannel();
return channel.getMembers();
// $input.removeClass('.hidden')
})
.then(function(members){
members.forEach(function(member){
console.log('member', member);
member.on('userInfoUpdated', function(){
console.log('userInfoUpdated', member);
})
})
})
.catch(function() {
// If it doesn't exist, let's create it
console.log("creating #{params[:chat_channel]} channel");
chatClient.createChannel({
uniqueName: "#{params[:chat_channel]}",
friendlyName: 'General Chat Channel'
}).then(function(channel) {
console.log("Created #{params[:chat_channel]} channel:");
console.log(channel);
chatChannel = channel;
setupChannel();
});
});
}
function setupChannel() {
chatChannel.join().then(function(channel) {
printMessage(username + ' joined the chat.');
chatChannel.on('typingStarted', showTypingStarted);
chatChannel.on('typingEnded', hideTypingStarted);
chatChannel.on('memberJoined', notifyMemberJoined);
chatChannel.on('memberLeft', notifyMemberLeft);
chatChannel.on('memberUpdated', updateMemberMessageReadStatus);
});
chatChannel.on('messageAdded', function(message) {
printMessage(message.author + ": " + message.body);
});
}
function updateMemberMessageReadStatus(member){
console.log('memberUpdated');
console.log('member.lastConsumedMessageIndex', member.lastConsumedMessageIndex);
console.log('member.lastConsumptionTimestamp', member.lastConsumptionTimestamp);
}
function leaveCurrentChannel() {
if (chatChannel) {
chatChannel.leave().then(function (leftChannel) {
console.log('left ' + leftChannel.friendlyName);
leftChannel.removeListener('messageAdded', function(message) {
printMessage(message.author + ": " + message.body);
});
leftChannel.removeListener('typingStarted', showTypingStarted);
leftChannel.removeListener('typingEnded', hideTypingStarted);
leftChannel.removeListener('memberJoined', notifyMemberJoined);
leftChannel.removeListener('memberLeft', notifyMemberLeft);
leftChannel.removeListener('memberUpdated', updateMemberMessageReadStatus);
});
}
}
function showTypingStarted(member) {
console.log('somebody is typing');
$('#is_typing').html(member.identity + ' is typing...');
}
function hideTypingStarted(member) {
$('#is_typing').html('');
}
function notifyMemberJoined(member) {
console.log('notifyMemberJoined');
printMessage(member.identity + ' joined the channel');
}
function notifyMemberLeft(member) {
console.log('notifyMemberLeft');
printMessage(member.identity + ' left the channel');
}
$input.on('keydown', function(e) {
if (e.keyCode == 13) {
chatChannel.sendMessage($input.val());
$input.val('');
} else {
//console.log('typing');
chatChannel.typing();
}
});
window.addEventListener("beforeunload", function (e) {
// var confirmationMessage = "\o/";
(e || window.event).returnValue = leaveCurrentChannel(); //Gecko + IE
return leaveCurrentChannel(); //Webkit, Safari, Chrome
});
});
and i've take alook to the console to see if my
console.log('userInfoUpdated', member);
or these guys
console.log('memberUpdated');
console.log('member.lastConsumedMessageIndex', member.lastConsumedMessageIndex);
console.log('member.lastConsumptionTimestamp', member.lastConsumptionTimestamp);
and they are never fired, during my test on the chat events, and i'm confused on how exactly i'm going to display how my users online or the status of a message is read or unread
so please enlighten me on the case, thank you
Twilio developer evangelist here.
According to the JS docs for the latest version of Twilio Chat, the event you need to listen for on members is just called 'updated'. So, listening for 'userInfoUpdated' won't work.
I would also recommend that within this code:
chatChannel.join().then(function(channel) {
//...
chatChannel.on('memberUpdated', updateMemberMessageReadStatus);
//...
})
you use the channel passed to the callback, rather than the original chatChannel object. Like this:
chatChannel.join().then(function(channel) {
//...
channel.on('memberUpdated', updateMemberMessageReadStatus);
//...
})
I don't know if this will fix the issue, but I can't think of anything else right now.

Check a Boolean value from database at the start of an app then load terms and condition page if false, load menu page if true

Is this possible?
Before any page loads, could I run JavaScript code to check what the value in a database is, then open the relevant page?
Here is my code so far:
function onDeviceReady() //Phone gap is ready
{
try
{
db = openDatabase('cuopioid', '1.0', 'cupioids application database',
2 * 1024 * 1024);
} catch (e)
{
// Error handling code goes here.
if (e == INVALID_STATE_ERR)
{
// Version number mismatch.
alert("Invalid database version.");
}
else
{
alert("Unknown error " + e + ".");
}
}
console.log("DATABASE Created!");
db.transaction(createTableTerms, errCB, console.log("MEDICINES Table Created!"));
$('#btnaccept').on('click', acceptTerms);
}
The code below creates the database (if it isn't there already)
function createTableTerms(tx)
{
tx.executeSql('CREATE TABLE IF NOT EXISTS TERMS (id unique, status boolean)');
tx.executeSql('INSERT INTO TERMS (id, status) VALUES (0, 0)');
console.log("TERMS Table Created!");
}
I have created this function which selects the rows form the database if it is set to true, then if the results has 1 record I want it to open the menu page, if it has no results it means the terms and conditions haven't been accepted previously:
function checkTerms(tx)
{
db.transaction(function(tx)
{
tx.executeSql('SELECT * FROM TERMS WHERE status=1', [],console.log("check terms"), errCB);
});
var len = results.rows.length;
if (len = 1)
{
console.log("accepted previously - menu page");
}
else
{
console.log("termsandconditions page");
}
}
I am not sure where to put this checkTerms(tx) function
I solved this problem by creating a new JavaScript file which runs when a html page lodes (start of the <head> tag
Which opens the database
Runs the SQL query to find the value
Opens the relevant page depending on the result
It still displays the page (half a second at most) when I load the page, but it does what I want
Here is the code:
try
{
db = openDatabase('cuopioid', '1.0', 'cupioids application database',
2 * 1024 * 1024);
} catch (e)
{
// Error handling code goes here.
if (e == INVALID_STATE_ERR)
{
// Version number mismatch.
alert("Invalid database version.");
}
else
{
alert("Unknown error " + e + ".");
}
}
checkTerms();
function checkTerms(tx)
{
db.transaction(function(tx)
{
tx.executeSql('SELECT * FROM TERMS WHERE status=1', [], openPage, errCB);
});
}
function openPage(tx, results)
{
var len = results.rows.length;
if (len = 1)
{
getDrugs();
window.location.href = "#page1"
console.log("accepted previously - menu page");
}
else
{
window.location.href = "#page0"
console.log("termsandconditions page");
}
}
Another way to solve this may of been to write a php page as kind of a clearing house based on your database values, then redirect the user to the relevent page. You could do this with ajax and the user wouldn't momentarily see the wrong page either.

SQLite database in Javascript locally

I'm using a PhoneGap project on XCode.
I am trying to connect to a SQLite databse by using Javascript.
I have made a file "myDatabase.sqlite" in an SQLite tool. Now my question is how do I open that database in my code? Right now I'm using the following code:
var db;
var shortName = 'myDatabase';
var version = '1.0';
var displayName = 'myDatabase';
var maxSize = 65535;
db = openDatabase(shortName, version, displayName,maxSize);
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM User;', [],
function(transaction, result) {
if (result != null && result.rows != null) {
for (var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
alert(row.ID);
}
}
}, errorHandler);
}, errorHandler, nullHandler);
The problem is that the database is empty because when i run it it gives the error 'No such table'.
I think it created a new database named "myDatabase" and thats why it has no tables.
Does anyone know how I can open my file with all the tables in it?
Thanks!
This script will help you:
<script type="text/javascript">
function createDatabase(){
try{
if(window.openDatabase){
var shortName = 'db_xyz';
var version = '1.0';
var displayName = 'Display Information';
var maxSize = 65536; // in bytes
db = openDatabase(shortName, version, displayName, maxSize);
}
}catch(e){
alert(e);
}
}
function executeQuery($query,callback){
try{
if(window.openDatabase){
db.transaction(
function(tx){
tx.executeSql($query,[],function(tx,result){
if(typeof(callback) == "function"){
callback(result);
}else{
if(callback != undefined){
eval(callback+"(result)");
}
}
},function(tx,error){});
});
return rslt;
}
}catch(e){}
}
function createTable(){
var sql = 'drop table image';
executeQuery(sql);
var sqlC = 'CREATE TABLE image (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, image BLOB )';
executeQuery(sqlC);
}
function insertValue(){
var img = document.getElementById('image');
var sql = 'insert into image (name,image) VALUES ("sujeet","'+img+'")';
executeQuery(sql,function(results){alert(results)});
}
<input type="button" name='create' onClick="createDatabase()" value='Create Database'>
<input type="button" name='create' onClick="createTable()" value='create table'>
<input type="button" name='insert' onClick="insertValue()" value='Insert value'>
<input type="button" name='select' onClick="showTable()" value='show table'>
<input type="file" id="image" >
<div result></div>
</script>
To download the code go visit url:
http://blog.developeronhire.com/create-sqlite-table-insert-into-sqlite-table/
myDatabase and myDatabase.sqlite are 2 different filenames, update your code to reference the correct filename with extension.
SQLite does automatically create a new empty database if you try to open a database that doesn't exist.
In my sqlite code I am using three js file for controlling sqlite one for debugging purpose, one for executing querys and another one for initilize the database and create basic tables.
debug.js
startup.js
query.js
Reference URL is http://allinworld99.blogspot.in/2016/04/sqlite-first-setup.html
startup.js
var CreateTb1 = "CREATE TABLE IF NOT EXISTS tbl1(ID INTEGER PRIMARY KEY AUTOINCREMENT, CreatedDate TEXT,LastModifiedDate TEXT, Name TEXT)";
var CreateTb2 = "CREATE TABLE IF NOT EXISTS tbl2(ID INTEGER PRIMARY KEY AUTOINCREMENT, CreatedDate TEXT,LastModifiedDate TEXT,Mark INTEGER)";
var DefaultInsert = "INSERT INTO tbl1(CreatedDate,Name) select '" + new Date() + "','Merbin Joe' WHERE NOT EXISTS(select * from tbl1)";
var db = openDatabase("TestDB", "1.0", "Testing Purpose", 200000); // Open SQLite Database
$(window).load(function()
{
initDatabase();
});
function createTable() // Function for Create Table in SQLite.
{
db.transaction(function(tx)
{
tx.executeSql(CreateTb1, [], tblonsucc, tblonError);
tx.executeSql(CreateTb2, [], tblonsucc, tblonError);
insertquery(DefaultSettingInsert, defaultsuccess);
}, tranonError, tranonSucc);
}
function initDatabase() // Function Call When Page is ready.
{
try
{
if (!window.openDatabase) // Check browser is supported SQLite or not.
{
alert('Databases are not supported in your device');
}
else
{
createTable(); // If supported then call Function for create table in SQLite
}
}
catch (e)
{
if (e == 2)
{
// Version number mismatch.
console.log("Invalid database version.");
}
else
{
console.log("Unknown error " + e + ".");
}
return;
}
}
debug.js
function tblonsucc()
{
console.info("Your table created successfully");
}
function tblonError()
{
console.error("Error while creating the tables");
}
function tranonError(err)
{
console.error("Error processing SQL: " + err.code);
}
function tranonSucc()
{
console.info("Transaction Success");
}
query.js
function insertquery(query, succ_fun)
{
db.transaction(function(tx)
{
tx.executeSql(query, [], eval(succ_fun), insertonError);
});
}
function deletedata(query, succ_fun)
{
db.transaction(function(tx)
{
tx.executeSql(query, [], eval(succ_fun), deleteonError);
});
}
function updatedata(query, succ_fun)
{
db.transaction(function(tx)
{
tx.executeSql(query, [], eval(succ_fun), updateonError);
});
}
function selectitems(query, succ_fun) // Function For Retrive data from Database Display records as list
{
db.transaction(function(tx)
{
tx.executeSql(query, [], function(tx, result)
{
eval(succ_fun)(result.rows);
});
});
}
I had same problem and I found out that you cannot use your sqlite db like this.
I used chrome and I found out that Chrome stores DBs in "C:\Users\%USERNAME%\AppData\Local\Google\Chrome\User Data\Default\databases".
There is a Databases.db that Chrome uses for managing DBs.
If you want to use your db you should add a record into Databases.db and put your file in "file__0" directory and rename it (your db file) to the id that is assigned to that record.

Categories