Home » Android » javascript – Reading and writing from localStorage?

javascript – Reading and writing from localStorage?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I just started to study Phonegap + jQuery Mobile and HTML5,, so don’t loose your nerve with my idiocy!

Could somebody tell me why this is not working? When I am using a variable from localStorage, I just get an empty screen when pressing the button, but when using a variable temperature=”100″, it is working fine. Android 4.1.

<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
  window.localStorage.setItem("temperature", "100");
  var temperature = window.localStorage.getItem("temperature");
}
</script>
<div data-role="content">
  <p>Working or not?</p>
  <button onclick="myFunction()">Try it</button>
  <p id="testi"></p>
<script type="text/javascript">
  function myFunction() {
    //var temperature = "100";----> This is working!
    document.getElementById("testi").innerHTML = temperature;
  }
 </script>
</div>

Another question: How to handle variables between pages in Windows Phone? They are not supporting localStorage, so is there another way to handle this if you haven’t got db-connection?

Thanks!

Sami

How to&Answers:

temperature is local to the scope of the onDeviceReady function. That is, once the function is over, it’s gone.

You have two options:

// Make it global
var temperature;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
  window.localStorage.setItem("temperature", "100");
  temperature = window.localStorage.getItem("temperature");
}

or:

// Retrieve it in myFunction
function myFunction() {
  var temperature = localStorage.getItem("temperature");
  document.getElementById("testi").innerHTML = temperature;
}

For a good list of examples of function scope, try this answer.