Search icon CANCEL
Cart icon
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Learning Hub
Free Learning
Arrow right icon
Creating Mobile Apps with Appcelerator Titanium
Creating Mobile Apps with Appcelerator Titanium

Creating Mobile Apps with Appcelerator Titanium: There's no better way to learn Titanium than by using the platform to create apps for iPhone, iPad, and Android, and this tutorial lets you do exactly that. It's a truly hands-on approach that covers all the essential bases.

By Christian Brousseau
€28.99 €19.99
Book Oct 2013 318 pages 1st Edition
€28.99 €19.99
€14.99 Monthly
€28.99 €19.99
€14.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now
Table of content icon View table of contents Preview book icon Preview Book

Creating Mobile Apps with Appcelerator Titanium

Chapter 1. Stopwatch (with Lap Counter)

For our very first application, we will be building a standalone stopwatch. It will provide basic functions such as starting, pausing, and resetting. We will also provide the possibility of saving the lap time and displaying it in a list. This first example is pretty straightforward, but after going through the steps of building the application, we will be able to cover the different interactions between user interface (UI) elements (for buttons and display items) and data structures (for keeping tabs on our lap times).

By the end of this chapter, you will have learned the following concepts:

  • Creating labels, buttons, and views

  • Styling them and placing them on the screen

  • Creating interactions between UI elements

  • Creating a table view (that scrolls) and adding rows to it

  • Using Titanium's logging API

Creating our project

Since this is the book's very first mobile application, we will go through the whole project creation process. For those of you who are already familiar with Titanium Studio, you can glance over this section in order to get the information you need. As for those of you who haven't delved into Titanium development yet, this will be a good walkthrough. Once you know how to create a project, you will be able to repeat the operation for every application from this book.

Once you have launched Titanium Studio, navigate to File | New | Mobile Project. In the Classic section, select the Default Project template and then click on Next >.

Fill out the Wizard form with the following information:


Value to enter

Project name



You can follow either one of the ensuing steps:

  • Create the project in your current workspace directory by selecting the Use Default Location checkbox

  • Create the project in a location of your choice

App Id


Company/Personal URL

Titanium SDK Version

By default, the wizard will select the latest version of the Titanium SDK, which is recommended (as of this writing, we are using Version 3.1.3 GA)

Deployment Targets

Select iPhone and Android

Cloud Settings

Uncheck the Cloud-enable this application checkbox

Here is the new Mobile Project wizard populated with the information that we covered in the preceding table:


Once you have assigned an App ID to a project, you cannot change it. The reason for this is because, during its creation, Titanium generates a guID (a technical key if you will). So if you were to change an application's App ID, it wouldn't match the guID anymore. Therefore, it is recommended that if you ever needed to change an App ID, simply create a new project and move the source files into this newly created project.

What have we here?

The wizard created several files and directories. We will cover what those files are as we go forward, but for now let's just turn our attention to the ones that we will focus on in this chapter:

  • tiapp.xml: It contains the application's metadata. This ranges from description, technical IDs, and custom settings, to name a few.

  • app.js: It contains the source code for our application.


    Now technically, this is already an application. If we were to run the generated code, we would have a fully functioning application. Of course, at this point in time, it is pretty rudimentary.

The UI structure

Before we start placing UI elements on the screen, we need to have a coherent vision of how the controls will be placed on the screen. Since Titanium Studio does not provide us with a visual editor (as of writing this book), we need to determine where the controls will be placed (x and y coordinates) and how big they will be (width and height).

Our application's user interface will comprise of a single window and will be divided into three sections (views). Inside these views, we will place controls such as labels, buttons, and a scrolling list view.

The following figure is a visual representation of how the user interface elements will be stacked atop one another:

Why do we use views?

Views act as containers; they are usually used to group controls together and can be more easily moved around the screen if needed. One very simple example for this would be a toolbar; it is nothing else than a panel containing buttons when you think of it. Now, if you need to change the location of the toolbar on your screen, you can simply move the container, not every single button. A window is a top-level container that can contain other views. The major difference is that it can be opened and closed. Opening a window will load all of its containing views; closing that same window will automatically remove the views contained in it.


For developers coming from the Java or .NET world, views would be equivalent to Panels. As for developers more familiar with HTML, they can be considered as DIV tags.

Now on to the code

As mentioned earlier in this chapter, all of the source code for the application is located in a single file (app.js). For every chapter in this book, we will delete all of the code contained in this file and replace it with our own. We will iterate on it until we have a complete working application.

It all starts with a window

Now that we have opened the app.js file and cleared all of its content, we can start working on a clean slate.

So the very first thing that we need in every application is a Window object. Every application today has at least one window. Some of them can fill the entire screen, have no title whatsoever, or even be transparent. But they are windows nonetheless.

The Titanium API provides us with several functions to create our UI objects. They are usually contained in the Titanium.UI namespace. Think of it as a package where you store functions that share a similar domain (such as User Interface, Geolocation, and Media management).

We create the window using the Ti.Ui.createWindow function. We want it to have a white background color and a vertical layout. Since we want to interact with our window later on in the code, we store its reference into a variable named win.

var win = Ti.UI.createWindow({
  backgroundColor: '#ffffff',
  layout: 'vertical'


Some of you may have noticed that we used the Ti.UI prefix instead of Titanium.UI. This is just a shortcut in order to make the code more readable. Both forms will work and behave in the same manner when building the application.

We added the layout property as an extra property to make sure that components will be stacked below one another. Thus, we're making sure that none of them will overlap. Different applications will have different needs, but in this specific case, it is appropriate.

Displaying the current time with big numbers

The main function of a stopwatch is to display the current time; for this, we will use a Label component. In order to give a visual effect of having light text over a dark background, we will put this label in a container view as explained in The UI structure section of this chapter.

So first, we create our container view. We want to position it at the very top. It will fill the entire width of the screen and will take up 30 percent of the screen's height.

var timeView = Ti.UI.createView({
  width: '100%',
  height: '30%',
  backgroundColor: '#1C1C1C'

Then, we want to create a label that will display the timer itself. The label object has more than 50 properties that can affect its appearance and behavior, so we won't go over all of them at this stage. What is important to remember here, is that we want it to have a large font (to display big numbers), and we want the text to be centered. We will also give a default value of READY? for when the counter is not running.

var label = Ti.UI.createLabel({
  color: '#404040',
  text: 'READY?',
  height: Ti.UI.SIZE,
  textAlign: 'center',
    fontSize: '55sp',
    fontWeight: 'bold'


Instead of specifying the height of the label, we used the Ti.UI.SIZE constant. This means that the control will adapt its size automatically to fit its content. This is particularly useful when we can't predict how much content will have to be displayed at runtime.

Now that both controls have been created, we need to add them to our window. As explained earlier, first we add the Label object to its container view:


Then, we add this same container view to our window:


Finally, we show the window using the open function:;

We can now do our first run

We can launch the application using the Run button from the App Explorer tab (on a simulator/emulator, or directly on a device). To see your code in action, simply click on the Run button, select where you want to run it, and the application will start (provided the code has no errors).

Our very first run shows our main window (with a white background), our container view (with a dark background), and our label showing READY? on the screen, as shown in the following screenshot:

This is not much yet, but we are getting there.

Starting and stopping the stopwatch

Now that we can show the time on our stopwatch, we need some way to start and stop it. To do this, we will use two button components. Buttons are pretty straightforward; the user touches it, an event occurs, and an action is performed.

As we want our buttons to be horizontally aligned, it makes perfect sense to group them inside a view. This view will act as a toolbar. It will fill the entire width of the screen, occupy 10 percent of the screen's height, and have a horizontal layout. The buttons are laid out from left to right.

var buttonsView = Ti.UI.createView({
  width: '100%',
  height: '10%',
  layout: 'horizontal'

Now, we need a button to start the stopwatch and another one to stop it. Much like labels, buttons have a lot of properties, so we won't go over all of them here. What is important here, is that they each have a different title (this is what the user sees on the button), and they each take up about 50 percent of the screen's width. Also, they each have different colors but share the same font.

var buttonStartLap = Ti.UI.createButton({
  title: 'GO!',
  color: '#C0BFBF',
  width: '50%',
  height: Ti.UI.FILL,
  backgroundColor: '#727F7F',
  font: {
    fontSize: '25sp',
    fontWeight: 'bold'


Notice that we defined the font size in sp units—also known as Scale-independent Pixels; an abstract unit that is based on the physical density of the screen. It is recommended to use this unit when specifying font sizes so they will be adjusted for both the screen density and the user's preference.

var buttonStopReset = Ti.UI.createButton({
  title: 'STOP',
  color: '#C0BFBF',
  width: '50%',
  height: Ti.UI.FILL,
  backgroundColor: '#404040',
  font: {
    fontSize: '25sp',
    fontWeight: 'bold'


Contrary to our timer label, the height property uses the Ti.UI.FILL constant, which means the buttons will grow to fill their parent's height (the toolbar view's height).

Notice that we didn't give any x position for the buttons. That's one advantage of using the layout property since it takes care of it for us.

Once the buttons are created, we simply add them to their parent view and then add this same parent to the main window, as shown in the following code:


We see the buttons, but they don't do much yet!

Once we have added our buttons, we can run our application once again, and we will see our newly added buttons. But at this point in time, they have no code behind them, as shown in the following screenshot:

Let's start with the GO! button. We want it to start counting when the user presses it. So to achieve this, we need to add an event handler that will be triggered when the user presses the button.

Titanium provides us with a simple function named addEventListener. This function has two parameters:

  • The event's name we want to handle (click, swipe, pinch, and so on)

  • The function that will be executed when the event occurs

For our two buttons, we add event handlers for the click event. Once this event is caught, the code contained in the function (passed as a second parameter), will be executed, as shown in the following code:

ButtonStartLap.addEventListener('click', function(e) {

ButtonStopReset.addEventListener('click', function(e) {
  label.text = 'READY?';


We could have also used an already existing function and reused it as our second parameter. This becomes useful when you want to reuse the same code for different events.

var alertFunc = function(e) {
    alert('Reusable code');

buttonStartLap.addEventListener('click', alertFunc);

Stopwatch is not defined, but it's okay

If you have tried running your code after adding event handlers, you will be shown an error message related to the fact that the stopWatch object is undefined. That's because there is no such out of the box feature in Titanium. Therefore, we will have to create our own.

It's quite simple really; it has four functions in total, as shown in the following table:

Function name

What it does


Starts the watch.


Stops the watch.


Returns a human-readable version of the elapsed time (in the 00:00:00:00 format). It has to work even while running.


Resets the watch to 0.

It also has to provide a listening mechanism in order to be able to perform an action at a specific interval (every 10 milliseconds in our case).


We are not going to cover the code from these functions in this book, since there are already plenty of JavaScript examples available on the web or the Internet. Also, putting the code used to calculate the difference between two timestamps would prove pretty much impossible to read on paper.

You can develop your own implementation, and as long as your code provides the methods needed, it will integrate seamlessly into the existing code.

But we took the liberty of providing one in the application's code, which is available on the public GitHub repository at

To use the library provided with the sample, we have to do the following:

  1. Load the stopwatch functionality contained in the stopwatch.js file located next to our app.js file. We can do this using the require function that follows the CommonJS pattern. There is a lot of documentation available regarding this pattern, and we will cover this topic in a chapter as we move forward. But for now, just see it as a way to load a feature that is contained in another file.

    var Stopwatch = require('stopwatch');
  2. We then need to create a function that will be triggered every time the stopwatch reaches a fixed duration in milliseconds (10 should allow us enough precision, without having a huge impact on performance). It contains only one statement that updates the value of the label with the current time.

    function stopwatchListener(watch) {
      label.text = watch.toString(); 


    Since it is called repeatedly, it is recommended that such a function performs only small operations to avoid degrading the performance.

  3. Then, we create a stopwatch object by specifying the listener function that will be attached to it (stopwatchListener) and the interval between calls (10 milliseconds), as shown in the following code:

    var stopWatch = new Stopwatch(stopwatchListener, 10);

With this code in place, we already have a fully-functioning stopwatch application that we can use. If we press the GO! button, the timer will start. If we press the STOP button, it will stop. And if we press the Go! button again, the timer will continue from where it was when it stopped.

Keeping up with lap times

Since we now have a working stopwatch application, we can implement more advanced features. One of those new features is the ability to keep a track of each lap and later on being able to view those laps.

The way that this feature will be presented to a user is quite simple. When the timer is running, the user has the ability to press a button. When this button is pressed, the application saves the current value on the timer and adds it to a list, without affecting the stopwatch counter in progress. The user can use this feature for an unlimited number of times, as long as the stopwatch is running.

Capturing lap times

Our application has only two buttons, and in the interest of good design, we will reuse those buttons so that they can offer other features when not in use. Therefore, the GO! button will become the LAP! button once the counter is started.

To keep track of whether the timer is already running or not, we will simply use a Boolean variable:

var isRunning = false;

We must modify our event listener for the GO! button to reflect what we want to achieve. We first check whether the timer is already running. If that is not the case, we change the variable's value so we know it is now running. We then change the button's title and start the timer, as shown in the following code:

buttonStartLap.addEventListener('click', function(e) {
  // If the timer is running, we add a new lap
  if (isRunning) {;
  } else {
    // If the clock is not ticking, then we start it
    isRunning = true;
    buttonStartLap.title = 'LAP!';
    buttonStopReset.title = 'STOP';

If it is already running, it means that we want to save a lap time. In this instance, we just log its value to the console using the logging function.


Titanium's logging API is a very useful feature that allows displaying messages to the console without having to resort to alert dialogs or other obscure mechanisms. It also allows us to assign different severity levels depending on the messages we want to log (info, warn, error, debug, and trace).

After the first run and a few laps, we will have an output to the console that will look like this:

[INFO] 00:01:17:37
[INFO] 00:02:53:19
[INFO] 00:04:06:93
[INFO] 00:06:11:52

This is not much to show for now, but the feature is there nonetheless.

Showing lap times in a scrollable list

Now that we are able to gather lap times and log them to the console, we want to display those values in a scrollable list. This new TableView component will have a light background color. It will fill the entire width of the screen and will occupy all of the remaining available height of the screen.

var table = Ti.UI.createTableView({
  width: '100%',
  backgroundColor: '#C0BFBF'

Once the table view is created, we add it to the main window.


Now that we have our list on the screen, we need to replace the code section where we logged the time to the console earlier. Instead, we will create a TableViewRow object. Much like labels, they have many properties to customize their appearance and behavior. But those that deserve attention here, are:

  • title: It is the text displayed on the row.

  • leftImage: It is the image that will be displayed in front of the row text. Here, the image is in the Resources/images directory, but it could be located anywhere as long as it is somewhere under the Resources directory.

  • className: It is the unique row layout. It can be any string you want, as long as all of the rows that share the same layout have the same className property.


    Setting the className property is very important since it is used to optimize rendering performance. It enables the operating system to re-use table rows that are scrolled out of view to speed up the rendering of newly visible rows. So, always check that you assign this property if you encounter performance issues with table views (especially with a lot of rows).

Other properties are used for cosmetic purposes (in the context of this application).

buttonStartLap.addEventListener('click', function(e) {
  if (isRunning) {
    var row = Ti.UI.createTableViewRow({
      title: stopWatch.toString(),
      color: '#404040',
      className: 'lap',
      leftImage: '/images/lap.png',
        fontSize: '24sp',
        fontWeight: 'bold'

Finally, we want to add this newly created row to the table using the appendRow function.

  } else {
  // else code doesn't change

Resetting the timer

The reset button shares the same principle as the GO! button. When the timer is running, the button gives the ability to stop the timer. If it is already stopped, it can be used to reset the timer and empty the list of laps.

We check whether the timer is already running. If it is, we stop the timer, change the button title accordingly, and set the variable to false.

If it is not already running, we clear the table of all its rows. Notice that we don't really delete any row, but instead we assign its data with an empty array. Then, we reset the timer and update the label's text to its initial value.

buttonStopReset.addEventListener('click', function(e) {
  if (isRunning) {
    buttonStartLap.title = 'GO!';
    buttonStopReset.title = 'RESET';
    isRunning = false;
  } else {
    label.text = 'READY?';

Well, there you have it! A fully-featured, native mobile application that is fully compatible with iOS and Android devices with a single code base. All of this was made with less than 120 lines of code (including comments).

Here is our final stopwatch with the lap counter:


In this first chapter, we created an entire mobile application from scratch using Titanium Studio. We also saw how important it is to have a clear vision in terms of the user interface; otherwise, things can become complex when you need to move them around.

We also went through the process of creating our user interface using views, labels, buttons, and even a table view. We also learned how to style and place them to meet our needs. We managed to get those same components to interact with one another using events.

While testing and debugging our application, we had a brief introduction to Titanium's logging API.

In the next chapter, we will go over the use of audio files, including reading and writing them to the filesystem and table views.

Left arrow icon Right arrow icon

Key benefits

  • Walk through the development of ten different mobile applications by leveraging your existing knowledge of JavaScript
  • Allows anyone familiar with some Object-oriented Programming (OOP), reusable components, AJAX closures take their ideas and heighten their knowledge of mobile development
  • Full of examples, illustrations, and tips with an easy-to-follow and fun style to make app development fun and easy
  • Get empowered to build your own apps from the knowledge gained from this book


Smartphones and tablets have really changed the technological landscape over the last 3-4 years. Much like the web did in the last decade, these powerful tools have changed the way people communicate and access information. Such a wide market creates opportunities for developers who have the skills to develop mobile applications. "Creating Mobile Apps with Appcelerator Titanium" is a practical, step-by-step guide to building iPhone, iPad, and Android applications using JavaScript. This book will give you a solid grounding of the dos and don'ts of mobile development and also covers a lot of the functionalities offered by the Titanium platform. This book begins with a look at what the Titanium platform has to offer. By taking you through clear tutorials on developing each application step-by-step, it helps you to apply your newly acquired knowledge afterwards. The difficulty level gradually increases along the course of the book. Each application from this book covers different aspects of mobile development. Every chapter starts by defining the application's features as well as the user interface structure. Every single code section is then explained and put into context allowing you to gain a clear understanding of their purpose and functionality. The book takes a “small milestone” approach, allowing you to actually run the application and see the progression. Every step is accompanied by many screenshots so you can see the expected result on screen. You will learn everything you need to know to develop your very own mobile applications. The book takes a laid-back approach to Titanium development and provides information in a way designed to never overwhelm the reader with information and also uses clear diagrams, screenshots, and tips throughout.

What you will learn

Create full-fledged applications using native components Save your data using a database and interact with it using SQL Interact with web services to retrieve data from external sources Make your own adventure game (Japanese RPG style) Bring a friend along on your epic adventure by adding online multiplayer to your game Use Geolocation to interact localized data and display it on a map Store your information in a centralized form using Appcelerator Cloud Services (ACS) and share this information with other users Integrate your applications with popular social media sites such as Facebook and Twitter

Product Details

Country selected

Publication date : Oct 26, 2013
Length 318 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781849519267
Vendor :
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details

Publication date : Oct 26, 2013
Length 318 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781849519267
Vendor :
Category :
Languages :

Table of Contents

18 Chapters
Creating Mobile Apps with Appcelerator Titanium Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Author Chevron down icon Chevron up icon
About the Reviewers Chevron down icon Chevron up icon Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
1. Stopwatch (with Lap Counter) Chevron down icon Chevron up icon
2. Sili, the assistant that just listens Chevron down icon Chevron up icon
3. The To-do List Chevron down icon Chevron up icon
4. Interactive E-book for iPad Chevron down icon Chevron up icon
5. You've Got to Know When to Hold 'em Chevron down icon Chevron up icon
6. JRPG – Second to Last Fantasy Chevron down icon Chevron up icon
7. JRPG – Second to Last Fantasy Online Chevron down icon Chevron up icon
8. Social Networks Chevron down icon Chevron up icon
9. Marvels of the World around Us Chevron down icon Chevron up icon
10. Worldwide Marco Polo Chevron down icon Chevron up icon
References Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Top Reviews
No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial


How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to
  • To contact us directly if a problem is not resolved, use
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.