Phonegap - Local storage not working - Android - android

I'm using Local Storage to pass values between pages in order to create a scroll to effect (user clicks link and is scrolled to particular part of the page based on ID)
I was previously using cookies but that didn't seem to work on Android, I read that local storage was supported so switched over to that. It works completely fine when in the browser but as soon as its packaged as a native app I lose all functionality? The API states that it should be supported, any ideas?
Here's my code:
Base URL:
var storage = window.localStorage;
$("a.scroll_link").click(function(event) {
event.preventDefault();
var value = $(this).attr("id");
storage.setItem("key",value);
console.log(value);
window.location=$(this).attr("href");
});
Receiving URL:
$(function () {
var value = window.localStorage.getItem("key");
if (value != "" && value != "undefined" && value != null) {
var storage = window.localStorage;
storage.setItem("key",value);
var scroll_type = "";
if ($.browser.webkit) {
scroll_type = "body";
} else {
scroll_type = "html";
}
$(scroll_type)
.stop()
.animate({
//get top-position of target-element and set it as scroll target
scrollTop: ($("#" + value).offset().top - 25)
//scrolldelay: 1.5 seconds
}, {
duration: 1500,
complete: function () {
storage.removeItem("key");
},
});
}
});
The code works fine in the browser just not natively, any ideas?
Thanks,

Use document.addEventListener("deviceready", onDeviceReady, false) instead of $(function(){...}
http://docs.phonegap.com/en/2.5.0/cordova_events_events.md.html#deviceready

1.Glad to know you solve your first problem. As gmh04 say, I think you should replace your init event with 'deviceready' which is triggered when the app start running.
2.
You mean window.localStorage.getItem("key") return null in Receiving URL?
I do not exactly encounter a problem as what you describe. However, you may try to move your code in receiving url to the same page of base url. I have tried for times and be very sure that the localStorage will work in the same page.

I would like add that there's a bug on the 2.6.0 version of cordova.js that make localStorage don't work on Android:
https://issues.apache.org/jira/browse/CB-3063
On the 2.5.0 version it works perfectly, and it is already fix on the 2.7.0 rc.

Related

Nativescript-vue save cookies on Android

I'm creating a simple webview app using nativescript-vue where there is nothing else in the app except the webview that loads a website fullscreen.
On iOS it works great, I can log in to the website turn the app off and on and I'm still logged in.
On Android, the cookies are not saved and you have to log in again every time you turn the app off.
Any way I can enable cookies in the webview for Android?
I couldn't make it work with cookies, so I had to switch and use localstorage as a backup for saving tokens instead of cookies.
Here is how my final version looks:
<template>
<Page>
<WebView #loadStarted="onLoadStarted"
#loaded="onWebViewLoaded"
src="https://yoururl.com/"
/>
</Page>
</template>
<script>
import { isAndroid } from "tns-core-modules/platform"
export default {
methods: {
onLoadStarted (webargs) {
if (isAndroid) {
const webView = webargs.object;
webView.android.getSettings().setDomStorageEnabled(true) // This will enable local storage
}
},
onWebViewLoaded(webargs) { // I use this only to disable the default zoom buttons
if (isAndroid) {
const webView = webargs.object;
webView.android.getSettings().setDisplayZoomControls(false)
webView.android.getSettings().setBuiltInZoomControls(false)
}
},
}
};
</script>
Apparently, you should be able to enable cookies doing this (at least for newer SDK users):
webView.on(WebView.loadStartedEvent, (args) => {
webView.android.getSettings().setAcceptThirdPartyCookies(webView, true)
});
But that didn't work as expected as it seemed like sometimes it would save cookies and sometimes it won't or sometimes it would remove cookies (when you log out) and sometimes not.
I hope this info helps someone as it sure seems there is little to none info about this especially if you aren't much familiar with pure Java Android development.
This code should work
const webView = webargs.object;
if (android.os.Build.VERSION.SDK_INT >= 21) {
android.webkit.CookieManager.getInstance().setAcceptThirdPartyCookies(webView.android, true);
}

XMLHttpRequest in Cordova for android

I'm actually stuck with a problem. Building a app in Cordova, for Android. I need to download a PDF from a variable path in the server. With a documentation from Cordova said "Transition off of cordova-plugin-file-transfer", located here , I tried this:
var oReq = new XMLHttpRequest();
// Make sure you add the domain name to the Content-Security-Policy <meta> element.
oReq.open("GET", endereco, true);
// Define how you want the XHR data to come back
oReq.responseType = "blob";
oReq.onload = function (oEvent) {
var blob = oReq.response; // Note: not oReq.responseText
if (blob) {
console.log("WORKS??");
} else console.error('we didnt get an XHR response!');
};
oReq.send(null);
where "endereco" is a variable where I store the pdf path. So, I'm testing and testing, but maybe someone got some pointers in how to implement this. Right now it just log "WORKS??", so I actually connected successfully. But what now?
1 - so, I made a request, but the file was saved? Couldn't find nothing in my mobile. How can I save said blob in a folder, with the same name and extension from the server?
So, if someone can at least send me to some proper examples or documentation, it would help a lot. Right now I'm reading all on MDN Web Docs, but I'm fairly noob with this type of code :(
thanks in advance!
so, this is how it worked for me! Using the info from the official documentation at cordova, formerly named "cordova-plugin-file" (link), and the amazing info from this page with examples "CORDOVA FILE PLUGIN EXAMPLES" (link) it worked. It could use some cleanup and some error callbacks, but right now I can run this, and download and save an pdf to my android. Hope it helps someone! B-)
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
var fileURL;
var req = new XMLHttpRequest();
req.open("GET", endereco, true);
req.responseType = "blob";
req.onload = function (event) {
var blob = req.response;
console.log(blob.size);
console.log(blob.type);
console.log("WORKS!");
console.log(fileURL);
// cordova.file.etc is where you will save the file. In this case, inside the app folder, in the main storage in Android
window.resolveLocalFileSystemURL(cordova.file.externalApplicationStorageDirectory, function (directoryEntry) {
// the 'temp.pdf' is the name you want for your file.
directoryEntry.getFile('temp.pdf', { create: true }, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function (e) {
// great success!
console.log('Write of file completed.');
};
fileWriter.onerror = function (e) {
// Meh - fail
console.log('Write failed');
};
fileWriter.write(blob);
} );
} );
});
};
req.send();}

Adding record using Indexed DB in Cordova project

I've a problem adding a record from a form.
When I do clic in a button call to function "save":
var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
var dataBase = null;
function save() {
dataBase = indexedDB.open("bbdd", 1);
dataBase.onupgradeneeded = function (e) {
active = dataBase.result;
};
dataBase.onsuccess = function (e) {
console.log('Database loaded!');
var active = dataBase.result;
var data = active.transaction(["docs"], "readwrite");
var object = data.objectStore("docs");
var request = object.put({
idDoc: document.querySelector("#idDoc").value,
name: document.querySelector("#name").value,
});
request.onerror = function (e) {
alert(request.error.name + '\n\n' + request.error.message);
};
data.oncomplete = function (e) {
idDoc: document.querySelector("#idDoc").value = '';
name: document.querySelector("#name").value ='';
};
}
dataBase.onerror = function (e) {
console.log('Error loading database');
};
}
Ok. I testing in Chrome and Firefox (Windows XP) and works fine. Data are added to database and fields are cleared.
Now, I built cordova project and run it in a Nexus 5 (Android 5.0.1) with:
cordova run android --devices="myId"
In Nexus 5 donesn't work. When I do click in the button the mobile phone does nothing. Data aren't added to database and fields aren't cleared.
What am I doing wrong?
I have this problem, too. There seems to be a bug on Android 5.0.1 related to the browser storage. This problem happens with localStorage, webSQL and indexDB.
A lot of people are experiencing this: Android 5.0.1 localstorage not persistent.
I made a simple app just for testing. I open the app and I just simply do (I added the code when onDeviceReady - when cordova is loaded):
var a = window.localStorage.getItem('test');
alert(a); //will give you undefined first time
if (!a) {
window.localStorage.setItem('test','12345678');
alert(windows.localStorage.getItem('test');
//this will display 12345678 from localstorage evertime
}
If you close the app after 2 or 3 seconds (force-closing the app) and re-open it, the value of test from localstorage is still undefined. You can do this for 10 times and you will get undefined every time. If you wait 10 or 12 seconds after you open the app and get the alerts, you will notice that after restarting the app (force restart), the data is there and localStorage works correctly.
I tested this on Android 5.0.1 and I used cordova 3.6.3, cordova 4.0, cordova 5.0. I did the same test on a tablet with Android 4.4.2 and the localStorage is set correctly.

How to add sounds with JQM and IntelXDK

I am working on an app and using IntelXDK to build it. I need to play some sounds if conditions are met, first I have tried HTML5 with JS and on desketop it's working but when built, it has no sound...
First attempt - HTML5 & JS
<audio src="snd/yes.mp3" id="yes"></audio>
<audio src="snd/no.mp3" id="no"></audio>
if(condition) {
$('#yes').trigger("play");
} else {
$('#no').trigger("play");
}
Then I tried the native IntelXDK version that goes like this:
if(condition) {
intel.xdk.player.playSound("snd/yes.mp3");
} else {
intel.xdk.player.playSound("snd/no.mp3");
}
No only that it doesn't work but it also f***s up the rest of my code not allowing the popup and page change to trigger.
Does anyone know how to fix this ?
Do I need to preload the sounds before playing them?
**UPDATE
I just discovered that if I use the HTML5 Audio tags and I give links to the sounds inside my server, the sounds are working, but if I try to get the same sounds from my snd folder they won't work...why is that?
The problem is that your "root" is not where you think it is, so your "snd" directory is not being found. This problem varies, unfortunately, with each target, it is not something the XDK controls, it has to do with how Cordova apps are constructed. You can use these functions to locate the root of your files and that should help you make this work.
// getWebPath() returns the location of index.html
// getWebRoot() returns URI pointing to index.html
function getWebPath() {
"use strict" ;
var path = window.location.pathname ;
path = path.substring( 0, path.lastIndexOf('/') ) ;
return 'file://' + path ;
}
function getWebRoot() {
"use strict" ;
var path = window.location.href ;
path = path.substring( 0, path.lastIndexOf('/') ) ;
return path ;
}

Phonegap WP7 app not perform any functionality

I am working on Cordova hybrid mobile app currently am doing in android app it runs fine now when i make same app for window phone it is not perform any functionality.
for make WP8 I follow this link after that i copy my all file of www folder to new generated www in Visual Studio project.
But when i ran app it just shows its first page only and not performing any functionality.
So what steps did i miss ?
On the click of button I call following function
$('#contactBackupBtn').on('click',function(){
$('#p2').append("Going to be backup");
sm_sync.backupAllTheContacts(function(){
$('#p4').append("After Contact Backup Function Finished ");
});
});
From above function it calls the following one
backupAllTheContacts:function(callback) {
$('#p3').append("IN backupAllTheContacts");
navigator.contacts.find(["*"], function(contacts) {
$('#p3').append("IN Contact Success");
callback();
}, sm_sync.onError, {"multiple": true});
}
onError:function(error) {
$('#p1').empty();
$('#p1').append(error.code);
$('#p1').append(error.message);
}
When i execute it, it shows this message IN backupAllTheContacts and ths Going to be backup but not showing any success or error messages. what should i do to make it run.
(This is a small part of my app it is runnng perfact in Android Emulator but not n windows
I need help i am stuck here)
use console.log is not support in windows phone so use this and use localStorage like this. try to run on deviceready
document.addEventListener("deviceready", function () {
/* This is for Console.log support in WP */
if (typeof window.console == "undefined") {
window.console = {
log: function (str) {
window.external.Notify(str);
}
};
}
var key0;
/* manage localstorage this way */
if (typeof (window.localStorage) !== "undefined") {
localStorage.setItem('lastname', "Smith");
localStorage.firstname = "One";
if (localStorage.getItem('objectKey1') != null || localStorage.getItem('objectKey1') != undefined) {
key0 = window.localStorage.getItem('objectKey1');
}
}
},false);
When i build my WP8 app i ran into somewhat an issue same as this. it's because of the jQuery i used. Then i updated my jQuery to the latest and its all started working fine.
Please check the jQuery documentation and the version you are using. Or you just put up your code in here so that we can have a closer look.
"But when i ran app it just shows its first page only and not performing any functionality.
So what steps did i miss ?"
Without the code how can we say what steps did you missed ???

Categories

Resources