Titanium Mobile Platform API Guide
The Titanium platform provides support for various on-device platform capabilities. This guide provides documentation for using these capabilities in your application.
Database
Each Titanium application has access to an on-device SQLite database. This database is specific (and private) to your application and supports a large subset of the SQL-92 standard.
Using the Database API
Before you can use the Database API, your application will need to initially create your database. This is typically done once the first time the application is started on the device.
First, you'll want to open the Database. The first argument passed to open is your database name. You can open multiple databases in the same application, just make sure each one has it's own unique database name.
var db = Titanium.Database.open('mydb');
Second, you'll need to create your tables. SQL provides a way to only create tables if they don't already exist using the IF NOT EXISTS keywords in your create syntax. For example:
db.execute('CREATE TABLE IF NOT EXISTS DATABASETEST (ID INTEGER, NAME TEXT)');
Make sure the db variable is the variable returned from the Titanium.Database.open function call.
If you attempt to create a table that already exists (and omit IF NOT EXISTS), a JavaScript exception will be thrown. You can also catch this exception as an alternate way to determine if the table already exists.
Once you've created your tables (or on subsequent executions), you can now insert data or query for existing data. Let's insert some data into our DATABASETEST table created above.
db.execute('INSERT INTO DATABASETEST (ID, NAME ) VALUES(?,?)',1,'Name 1');
db.execute('INSERT INTO DATABASETEST (ID, NAME ) VALUES(?,?)',2,'Name 2');
db.execute('INSERT INTO DATABASETEST (ID, NAME ) VALUES(?,?)',3,'Name 3');
db.execute('INSERT INTO DATABASETEST (ID, NAME ) VALUES(?,?)',4,'Name 4');
The above code example will create 4 rows, each with a unique ID and name.
Notice that the parameters are passed in as separate arguments to the function and that there are ? for each position. You should generally use this syntax as opposed to manually string-concatentation of your SQL query. This will ensure that the values are properly escaped before inserting into the database.
You can determine the number of rows affected after an SQL exec by accessing the property rowsAffected. For example:
alert("You performed SQL on " + db.rowsAffected + " rows");
You can also determine the last row ID (primary key) of previous INSERT by accessing the lastInsertRowId property. For example:
alert("The last INSERT record had the ID: " + lastInsertRowId);
Querying for Data
To pull data from the Database, you'll need to use the SQL SELECT statement. For example, let's iterate over all the rows in the database we inserted above:
var rows = db.execute('SELECT * FROM DATABASETEST');
while (rows.isValidRow())
{
alert('ID: ' + rows.field(0) + ', NAME: ' + rows.fieldByName('name'));
rows.next();
}
// always close result set to free resources
rows.close();
In the above example, we iterate over all the results returns from the query using the ResultSet object. For each row, we can access the row data using either a field by index or by name. Fields are zero-based so make sure you use 0 (zero) for the first column. To move to the next row, make sure you call next on the result object. The result object will return false to isValidRow once you have reached the end.
To cleanup, make sure you always call close on your result set object to free resources.
Cleanup
When you're done with your Database, you should call close against the Database object returned from open. However, if your application uses the database often, it's OK to store the variable in a global variable (or better, a namespaced application variable) and re-use it. The database will automatically be closed when the application exists.
Sometimes it's nice to just delete all rows in a table. You can do this by executing:
db.execute('DELETE FROM DATABASETEST');
Or, if you want to complete delete your table, you can drop it using the following as an example:
db.execute('DROP TABLE DATABASETEST');
Using an existing SQLite Database
See how-to-add-existing-sqlite-database-to-a-project for more on how to use install to use an existing database.
Network
Titanium applications often need to either retrieve remote database using web services or send data from the phone to a remote web service. The Titanium.Network.createHTTPClient provides a cross-domain XHR implementation, meaning you can access any remote URI from your application with no security restrictions.
Create a Remote Request
To create a request to a remote web service, you first need to create an instance of an HTTP client using Titanium.Network.createHTTPClient and set up any specific headers or content-type.
var xhr = Titanium.Network.createHTTPClient();
The result will be an instance of the HTTPClient.
Once you have an instance, you'll need to open the connection passing the HTTP method (for example, GET or POST) and the URL.
xhr.open('GET','http://kyroc.net/jasonheart.php');
Most likely you'll want to know when you get a response (unless you're just simply sending data and don't care about what's returned).
You have two method for determining when you're completed.
Fine Grain State Callbacks
The first method provides fine-grained state changes for the connection. You set the onreadystatechange property to a function that will be invoked for each state change. For example:
xhr.onreadystatechange = function()
{
if (this.readyState == xhr.DONE)
{
alert(this.responseText);
}
};
The DONE property will equal the readyState property when the request has completed.
You can then access either the responseText which is the text result or the responseXML which is the response as a DOM document object. If you attempt to access the responseXML property for non-XML content, an exception will be thrown.
Higher level State Callbacks
The second method for state changes is to listen for the onload by assigned a function to this property. For example:
xhr.onload = function()
{
alert(this.responseText);
};
This method is much easier and is a short-hand for the example above and will only be called when the state is DONE.
Sending the Request
To send the request, we now have to call the send method on the HTTPClient object.
To send a data along with the request, you can pass data to the send method. The send method takes either a JavaScript object of key/value pairs. You can also pass a urlencoded string which will be used as the payload.
It's important to note that the send method is asynchronous (by default) unless you pass false to the third argument of open.
If you would like to send binary data, for example the result of a Camera, you can pass the result as the value part of a key/value pair in send.
For a more involved example:
Titanium.Media.showCamera(
{
success:function(image,details)
{
$("status").innerHTML="Uploading...."+image.url;
try
{
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function()
{
var xml = this.responseXML;
function getTextValue(n)
{
var s = '';
for (var c=0;c<n.childNodes.length;c++)
{
s+=n.childNodes[c].nodeValue;
}
return s;
}
var url=getTextValue(xml.documentElement.getElementsByTagName("mediaurl")[0]);
document.getElementById("status").innerHTML="<div>Done!</div><a href='"+url+"'>"+url+"</a>";
};
xhr.open("POST","http://twitpic.com/api/upload");
var un = $('username').value;
var pw = $('password').value;
xhr.send({media:image, username:un, password:pw});
$("status").innerHTML="Uploading...."+image.url;
}
catch(E)
{
Titanium.UI.createAlertDialog( {
title: "Error",
message: String(E),
buttonNames: ['OK']
} ).show();
}
},
allowImageEditing:true
});
In the above example, the Titanium.Media.showCamera method is invoked to show the system camera. After a successful picture is taken, the success callback function is invoked which will transmit the picture to TwitPic. This example assumes that the HTML contains two input fields with IDs username and password with the username/password of the TwitPic account.
Basic HTTP Authentication
For basic HTTP authentication, the username and password data is sent in the open request, not as data in the send request.
An example of basic authentication using Twitter:
var un = $('username').value;
var pw = $('password').value;
try {
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function() {
//do work on "this.responseXML"
};
xhr.open("GET","http://"+un+":"+pw+"@twitter.com/account/verify_credentials.xml");
xhr.send();
}
catch(err) {
Titanium.UI.createAlertDialog({
title: "Error",
message: String(err),
buttonNames: ['OK']
}).show();
}
Application Properties
Applications often need to persist configuration data or state available across restarts of the application. Developers can use the Database API to store complex data. To store simple properties, you can use the Properties API.
This API provides storage and retrieval of basic types such as integers, strings and lists.
For example:
Titanium.App.Properties.setString('String','I am a String Value');
Titanium.App.Properties.setInt('Int',10);
Titanium.App.Properties.setBool('Bool',true);
Titanium.App.Properties.setDouble('Double',10.6);
var html = '';
html+= 'String: ' + Titanium.App.Properties.getString('String') + '<br/>';
html+= 'Int: ' + Titanium.App.Properties.getInt('Int') + '<br/>';
html+= 'Bool: ' + Titanium.App.Properties.getBool('Bool') + '<br/>';
html+= 'Double: ' + Titanium.App.Properties.getDouble('Double') + '<br/>';
alert(html);
Titanium Mobile Dev Center