alok alok - 6 months ago 42
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

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"));
console.log(questions);

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