alok alok - 1 year ago 120
JSON Question

How to create offline database for Phonegap mobile application?

I am creating phonegap mobile app for Android and I need to store questions in offline mode with app. Can I use JSON for this. If yes please guide me how can I store my questions in separate text file and how can I access the specific question in my app from the container text file.

Answer Source

You can use localStorage to store your questions as an array of objects as follows:

questions = [
   { id : 1, text: "Question 1 text goes here" },
   { id : 2, text: "Question 2 text goes here" },
   { id : 3, text: "Question 3 text goes here" },
   { id : 4, text: "Question 4 text goes here" }

window.localStorage.setItem("questions" , JSON.stringify(questions));

And then to read it back you use JSON.parse();

questions = JSON.parse( window.localStorage.getItem("questions"));

P.S. data stored in localStorage doesn't expire and stays after your phonegap application is closed.