Saving data with Titanium mobile
Posted: July 15th, 2010 | Author: Giv | Filed under: Mobile, Tutorials | No Comments »In my previous post I talked about getting a simple table view up and running quickly using Titanium. A few people have asked me to continue the tutorial and explain how to save individual items and then display saved items in a separate window.
Saving data is quite simple. You first need to create the database and schema. You obviously only need to do this the first time the user opens your app. So in your app.js file you can do something like this:
1 2 | var db = Titanium.Database.open('mydb'); db.execute('CREATE TABLE IF NOT EXISTS SAVEDITEMS (NAME TEXT)'); |
This should look very familiar to you if you’re used to SQL. It first instantiates a database object then checks to see if the “SAVEDITEMS” table exists. If not, it will simply create it. If it does exist, it will just ignore that command. This will create a table with a single text field for storing the name of a selected item.
Now that we have our table set up, we can read and write to it whenever we like. If you wanted to save an item, you would do this:
1 | db.execute("INSERT INTO SAVEDITEMS ( NAME ) VALUES ('my cool item')"); |
To get a list of all items in the database:
1 2 | var rows = db.execute("SELECT * FROM SAVEDITEMS"); rows.close(); |
The last line is very important. You must close your query results to avoid memory leakage.
You can now loop through the saved items and stick them in a table view:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | // create blank table view var tableview = Titanium.UI.createTableView({}); Titanium.UI.currentWindow.add(tableview); // create an empty array var data = []; // get a list of all saved items var rows = db.execute('SELECT * FROM SAVEDITEMS'); // loop through all items while (rows.isValidRow()) { // add each item to the data array and set the table row title data.push({title:rows.field(0),hasChild:true}); rows.next(); } // load db data into the table view tableview.setData(data); rows.close(); |
That should help you get started. You can look at how to use events to save items and also check to see which items have already been saved so you don’t show the save button etc. Take a look at the demo app I’ve created to see how I handled the saving logic. Specifically the details.js file.
No Comments »