woolm110
woolm110

Reputation: 1204

Phonegap - Local storage not working - 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,

Upvotes: 5

Views: 8700

Answers (3)

fray88
fray88

Reputation: 820

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.

Upvotes: 1

Jack He
Jack He

Reputation: 1693

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.

Upvotes: 1

gmh04
gmh04

Reputation: 1351

Use document.addEventListener("deviceready", onDeviceReady, false) instead of $(function(){...}

http://docs.phonegap.com/en/2.5.0/cordova_events_events.md.html#deviceready

Upvotes: 2

Related Questions