Android : PhoneGap and Android localStorage

on Monday, September 22, 2014


I am using Cordova 2.2.0 and Eclipse to create an Android app that uses HTML5 localStorage. I've noticed a strange problem that I haven't seen asked on this website before. The app consists of 2 pages with a button on each. When one of the buttons is pressed it should increment the locally stored variable (window.localStorage.count) by +1 and alert me to its new value.


For instance when I first open the app and press the button on page1 twice, the variable should be equal to 2. Then when I navigate to the second page and press the button there twice again the variable is equal to 4. So far this works correctly the very first time I use the app after running it from Eclipse on my device, however the problem occurs when I go back to the first page again. If I press the button once (on page1) the variable is now 3 (only incremented from the value set on its page and ignoring page2) and if I navigate to the second page once again and press the button a single time I get a value of 5 as if ignoring what happens on the other page1. It seems the variable is being stored separately on each page and acts as 2 separate variables despite both pages being linked to the same javascript file.


This works perfectly using PhoneGap in iOS even if I quit the app and on web browsers that I've tested like Chrome and Safari. Can anyone describe why this behaviour is occurring? I've tried removing "window." from the localStorage part but this has not had an effect.


I'm using a Samsung Galaxy s3 mini with Android version 4.1.2. I'm also using regular jQuery in the app.


Javascript file



window.localStorage.count;
if(typeof window.localStorage.count === "undefined") {window.localStorage.count = 0)}

function incrementCount() {
window.localStoarge.count++;
alert(window.localStorage.count);
}


Page1 HTML



<button onClick="incrementCount()">Add to Count</button>
<button onClick="location.href='page2.html'">Go to Page 2</button>


Page2 HTML



<button onClick="incrementCount()">Add to Count</button>


In case it helps I only use one permission in the AndroidManifest.xml which is



<uses-permission android:name="android.permissions.ACCESS_NETWORK_STATE" />


Once again I can't explain why this is happening. It seems to work the first time I test the app but not after I navigate back to the first page subsequently. Thanks for your help.


0 comments:

Post a Comment