PhoneGap: Saving Arrays in Local Storage

One of a handful of local storage options for PhoneGap applications is the localStorage solution which is actually part of the W3C specs. It provides access to a W3C Storage interface since we are just dealing with HTML5 in PhoneGap. This is a good option for storing simple strings but what if we want to store more complex data structures but don’t want to be bothered with a SQLite database for our application? It’s actually possible to do this via some JSON trickery!

In this example, we will first initialize our Array object to hold all the data:

var gatheredPosts = new Array();

We can then create complex data structures and push these into our array for immediate use in the application – and to back up via local storage options for later. Here’s some dummy code which demonstrates this:

// let's imagine these "posts" come from a remote data call which has just returned
for (var i = 0; i < posts.length; i++) {
    gatheredPosts.push({title:posts[i].title, url:posts[i].url, content:posts[i].content});
}

At this point, we could attempt to write the array to local storage via the normal method... but this will not work with complex objects like arrays out of the box - and will fail to write the appropriate data:

window.localStorage.setItem("cachedPosts", gatheredPosts);

What we need to do to be able to save and retrieve complex array data is to extend the Storage prototype with new methods which will stringify our array data into JSON and also parse the stringified data into a new data object for retrieval. It's a lot simpler than it sounds. Just include these definitions in your JavaScript:

Storage.prototype.setArray = function(key, obj) {
    return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getArray = function(key) {
    return JSON.parse(this.getItem(key))
}

We can now use these new methods to properly store and retrieve our array structures!

Here we see array storage:

window.localStorage.setArray("cachedPosts", gatheredPosts);

And array retrieval:

gatheredPosts = window.localStorage.getArray("cachedPosts");

Not a bad solution :)

2 thoughts on “PhoneGap: Saving Arrays in Local Storage”

Comments are closed.