Restoring Application State on Phonegap - android

I've develop an Android app with phonegap, my app need to swicthing on the toggle button, then user can close the app and running it in background service. My problem is when I close the app and back to the app again, its back to the initial state with toggle button off.
So, My question is how can we saving/restroring app state on android and phonegap?
I've read this Save & restoring WebView in an embedded PhoneGap app , but I still don't understand about restoreFromPreferences() and saveToPreferences(out) Can anyone help?
*Sorry for bad english

As #geet said, localStorage is what you need to store datas and retrieve them later.
According to Phonegap website, localstorage provides access to a W3C Storage interface. You can read about it here : http://dev.w3.org/html5/webstorage/#the-localstorage-attribute.
To save a toggle button position this is what I do :
<script>
function onDeviceReady() {
// Set togglebutton to false default
var togglebutton = window.localStorage.getItem("togglebutton");
if (togglebutton==null) window.localStorage.setItem("togglebutton", 'false');
// Set default state
if (window.localStorage.getItem("togglebutton")=='true') {
$('#onoffswitch').attr("checked", "checked");
}
// Switch onoffswitch event
$('#onoffswitch').on('change', function(){
if ($(this).prop('checked')) {
window.localStorage.setItem("togglebutton", 'true');
} else {
window.localStorage.setItem("togglebutton", 'false');
}
});
}
</script>
Make sure in your HTML that your toggle element (form me a checkbox) isn't checked by default :
<input type="checkbox" name="onoffswitch" id="onoffswitch">
About Pause and Resume, you can perform actions when these events are called. To do this :
<script>
document.addEventListener("resume", yourCallbackFunction, false);
document.addEventListener("pause", yourCallbackFunction, false);
</script>

U can store any data in localstorage in your JS.
e.g
To save value of var username.
localStorage.setItem("username",edited_name);
To retrive
var getUser=localStorage.getItem("username");
hope it will help to u!!

function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener("pause", onPause, false);
function onDeviceReady() {
var pageNow = document.getElementsByTagName(body);
var currentPage = JSON.stringify(pageNow);
localStorage.setItem("uiState", currentPage);
}
function onPause() {
//retrieve info here
var pageShow = document.getElementsByTagName(body);
let techStack = localStorage.getItem("uiState");
// JSON.parse(techStack); //unnecessary because the parser will detect HTML
pageShow.innerHTML(techStack);
}
}
you can get the current state of the UI in any element, just use a different selector.
will update this answer to incorporate SQL later

Related

jQuery 'taphold' does not fire, while 'tap' does

In my flutter app I have html inside a webview and some javascript with jquery attached. I want to trigger different actions depending on if a list item receives 'tap' or 'taphold'. I'm using jquery-mobile 1.5.0-rc1.
My javascript is as follows:
$('div.board').on('taphold tap', 'div.thread, div.thread-special', function(event) {
console.log('event');
var $item = $(this); // The item that was clicked or held
var scope = $item.data('itemscope'); // No numbered IDs! You can find everything about the item
// etc.
var type = event.type;
if (type === 'tap') {
console.log('tap');
} else if (type === 'taphold') {
console.log('taphold');
}
});
When I tap, I can see a 'tap' in the console. When I taphold, nothing at all happens or appears on the console. Any idea why?

On Back button event Show confirm Yes,No option before closing app for window.open using Cordova InAppBrowser

Well i'm newbie & stuck at a point. And that might have simple solution as well..
I load a page using window.open using InAppBrowser, While user press hardware backbutton I want to show confirm message before app gets close. I tried some code...
Here is Code
index.html
$(document).ready(function() {
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var ref = window.open('http://stackoverflow.com/', '_blank', 'location=no,hardwareback=yes');
ref.addEventListener('loadstart', function(event) { SpinnerPlugin.activityStart("Initializing..."); });
ref.addEventListener('loadstop', function(event) { SpinnerPlugin.activityStop(); });
ref.addEventListener('loaderror', function(event) { alert('error: ' + event.message); SpinnerPlugin.activityStop();});
ref.addEventListener('exit', function(event) {
alert('Exit')
});
ref.addEventListener("backbutton", function () { //But This is not triggering...Don't know why..
onConfirm();
})
function onConfirm(button) {
if (button == 1){ //Yes button pressed...
navigator.app.exitApp();
} else{
return false;
}
}
}
});
Even I tried backbutton event of Cordova..
document.addEventListener("backbutton", onBackKeyDown, false); //Listen to the User clicking on the back button
function onBackKeyDown(e) {
navigator.notification.confirm("Are you sure you want to exit ?", onConfirm, "Confirmation", "Yes,No");
}
It gets triggered properly but after closing inner window..
So again in brief, I want to show same confirm box before closing inner window.
Note: I'm using Cordova 6.1.0
Thanks a-ton in-Advance
I tried this , it ll work,
document.addEventListener("backbutton", function(e){
navigator.notification.confirm("Are you sure you want to exit the application?",fnLogout,"Warning","Ok,Cancel");
}, false);
function fnLogout(button) {
if(button == 1) {
navigator.app.exitApp();
} else {
return;
}
}
EDIT:
it’s highly possible that overriding the back-button for the InAppBrowser in PhoneGap is not possible.
Try to get brief details in below link:
https://cordovablogsblogs.wordpress.com/2016/02/04/handle-android-back-button-on-phonegap-inappbrowser/
Thanks.

Android Appcelerator Get URL from remote URL in webview and open it in devices default browser or a new webview

My question is exactly the same as this one but for Android and not iOS.
Get URL from remote URL in webview and open it in safari
Anyone have an idea. I am creating a cross-platform app and I have used the Clayton's answer to get it to work for iOS with some tweaks to open with a controller. But when trying different methods on Android and it is not working. This is as close as I have gotten (which is what Aaron provided on that same page) and it is not quite right as it opens the remote web page in a new browser window as well in the apps webview:
$.floorView.addEventListener('load', function(e) {
if (e.url.indexOf("http") !== -1) {
// stop the event
e.bubble = false;
// stop the url from loading
$.floorView.stopLoading();
// open
Ti.Platform.openURL(e.url);
}
});
Thanks!
I'd listen to the beforeload event, although I'm not 100% sure if you can actually prevent the Webview from still continuing the load as well.
Another way would be to intercept these links via JS you load or inject (evalJS()) in the webpage. Then fire a Ti.App event and respond to it in Titanium.
The Titanium.UI.Webview has a specific property for intercepting links: onlink.
This is not implemented as an event because it is a callback and needs to return a boolean to tell the Webview whether or not to load the URL of the link.
Oddly, setting the onlink callback right away makes the URL immediately load in Safari, so I did it this way:
$.webview.addEventListener('load', function(e) {
$.webview.onlink = function(e) {
Ti.Platform.openURL(e.url);
return false;
};
});
You can of course check the e.url string and decide whether to open it internally or externally.
I think I may have figured it out. Thanks to those whose ideas and suggestions lead to this code.
It appears to be working as I want on iOS and Android. Any suggestions or issues that you guys have I would appreciate the feedback. Thanks!
if ("iOS") {
$.webView.addEventListener('beforeload', function(e) {
if (e.navigationType == Titanium.UI.iOS.WEBVIEW_NAVIGATIONTYPE_LINK_CLICKED) {
// stop the event
e.bubble = false;
// stop the url from loading
$.webView.stopLoading();
//opens up the clicked URL for bill in new webView
var link = e.url;
var args = {url: link,};
// open link in my default webView for iOS
var newWebView=Alloy.createController('defaultWebView', args).getView();
newWebView.open();
}
});
}
else if ("Android") {
$.webView.addEventListener('beforeload', function(e) {
if (e.url.indexOf("http") !== -1) {
function Parser(text) {
var html = text;
var urlRegex = /((http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?)/gi;
this.getHTML = function() {
return html;
};
} // end Parser
var parser = new Parser(e.url);
html = parser.getHTML();
if (html != "url of $.webView") {
// stop it from loding in current webView
$.webView.stopLoading();
// open link in browser
Ti.Platform.openURL(html);
}
}
});
}
else {
.....................
}

Cordova InAppBrowser Loading Spinner for Android

I've an app built with cordova and InAppBrowser. I'm trying to show a "loading spinner" in every page.
In iOS it's working well on every page I load, but Android fails.
On iOS I just edited self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] this line in CDVInappBrowser.m and works.
Does Android have a similar feature ?
Here is my code:
// Cordova is ready
function onDeviceReady() {
var ref = window.open("http://m.estadao.com.br/?load-all=true", "_blank", "location=no", "toolbar=no", "closebuttoncaption=a", "EnableViewPortScale=no");
navigator.notification.activityStart("Loading", "Loading...");
setTimeout(function(){
navigator.notification.activityStop();
}, 5000);
}
Check this plugin:
https://github.com/Paldom/SpinnerDialog
Working for me in Android. You should use this method to show a spinner with title and message:
window.plugins.spinnerDialog.show("Loading","Loading...");
Your code would be:
function onDeviceReady() {
var ref = window.open("http://m.estadao.com.br/?load-all=true", "_blank", "location=no", "toolbar=no", "closebuttoncaption=a", "EnableViewPortScale=no");
window.plugins.spinnerDialog.show("Loading","Loading...");
setTimeout(function(){
window.plugins.spinnerDialog.hide();
}, 5000);
}
Resvolvi dessa forma
//window.open Example
// Wait for device API libraries to load
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
// external url
// var ref = window.open(encodeURI('http://mfsom.com.br/'), '_blank', 'location=no','toolbar=no');
//relative document
ref = window.open('http://mfsom.com.br/','_self',',location=no');
ref.addEventListener('loadstart', loadstartCallback);
ref.addEventListener('loadstop', loadstopCallback);
ref.addEventListener('loadloaderror', loaderrorCallback);
ref.addEventListener('exit', exitCallback);
function loadstartCallback(event) {
showSpinnerDialog();
}
function loadstopCallback(event) {
hideSpinnerDialog();
}
function loaderrorCallback(error) {
console.log('Erro ao carregar: ' + error.message)
}
function exitCallback() {
console.log('O navegador está fechado...')
}
function showSpinnerDialog() {
navigator.notification.activityStart("Carregando..");
//$.mobile.loading("show");
}
function hideSpinnerDialog() {
navigator.notification.activityStop();
//$.mobile.loading("hide");
}
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener( 'resume', onResume.bind( this ), false );
// TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
};
As both the answers here use the activityStop() which is deprecated, use your own spinner which you use in your app to prevent InAppBrowser's blank opening screen
Open the InAppBrowser in using hidden=yes option and later in loadstop event listener show the InAppBrowser. Till then you can show your custom loader
var ref = window.open("http://m.estadao.com.br/?load-all=true", "_blank", "location=no,toolbar=no,closebuttoncaption=a,EnableViewPortScale=no,hidden=yes");
ref.addEventListener('loadstart', function() {
showLoader();//`showLoader()` is your own loader function to show loader within your app
});
ref.addEventListener('loadstop', function() {
ref.show();
hideLoader();//`hideLoader()` is your own loader function to hide loader within your app
});

Check if Cordova/Phonegap is correct

A simple question, how i can check if cordova is properly accessible and working in my html index file in android.
I tried searching for some syntax or code that can confirm but alas...
There are some functions that I am not able to access. Like navigator.connection.type gives me that type not defined of null..
So I am wondering if there is any way to check.
Thanks..
EDIT 1
$(document).one('pageinit', function(event) {
registerElementEvents();
validateFields();
// Check Internet Connection
checkConnection();
});
function checkConnection() {
//alert(window.top.navigator);
var objects = window.top.navigator;
for(var key in objects) {
var value = objects[key];
//alert(value);
}
if( !navigator.network )
{
// set the parent windows navigator network object to the child window
navigator.network = window.top.navigator.network;
}
// return the type of connection found
return ( (navigator.network.connection.type === "none" || navigator.network.connection.type === null ||
navigator.network.connection.type === "unknown" ) ? false : true );
}
There are lots of way to check
you can use the alert("your message"); so that you get a popup window in the function that
you want to work
Another way is using console.log("TESTING"); which will generate a log file. you can trace the log file too
for your nxt question regarding the connection type you can see and use this https://github.com/apache/cordova-plugin-network-information/blob/dev/doc/index.md
So reviewing the code it looks like the issue is that there is no check for the deviceready event.
Try something like this:
HTML:
<body onload="onLoad">
JS:
function onLoad() {
document.addEventListener('deviceready', deviceReady, false);
}
function deviceReady() {
registerElementEvents();
validateFields();
// Check Internet Connection
checkConnection();
}
I make use of a boolean value. When it is true, PhoneGap is propperly loaded.
// device ready
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.deviceReady = true;
}

Categories

Resources