Appcelerator Developer Blog

Updating to Android r22 Tools

Recently Google released an update (r22) to their Android developer tooling. This update has rearranged the directory structure of the tools and breaks the building of Android projects both from the CLI and inside Titanium Studio. Unless you need the updated functionality we recommend you hold off updating for now.

How do I know if I’ve run into this issue?

See TIMOB-13944. You’ll get a failure similar to “TypeError: argument of type ‘NoneType’ is not iterable”

How do I fix this problem?

There are a number of different ways to address the issue, depending on your goals:

If you want to use just the very latest version of the SDK, download the pre-release 3.1.1 build from http://builds.appcelerator.com.s3.amazonaws.com/index.html#3_1_X

If you need  to use prior versions of the SDK:


Featured Developer – ArtistBox

Today’s featured blog post comes from the creators of ArtistBox, Lucica Ibanescu and Titan Dan Tamas. ArtistBox is a sexy Titanium app that provides detailed information, news and music from your favorite artists. Learn more about their experience with Titanium below.


We’d like to share with you our story on how we built ArtistBox and to give you some insights on how we solved the (not a few) issues that we had.

What’s ArtistBox?

Artistbox is an iPhone application that finds the most complete information about your favourite artists: their biography, discography, news, concerts in your area and worldwide, videoclips, pictures and similar artists.

We strive to gather way more information than any other music discovery app on the market – for example by adding up-to-date news or hi-res pictures – and for the next versions we will add more cool features.

Why Titanium and why not native?

The app has two components: a client side – the app itself – and a server side. The whole app was build in five months by just two programmers @dan_tamas and @nosoloweb and we feel that coding it in objC wouldn’t have given us such an advantage from the time point of view.

There are many other reasons we chose Titanium:

  • depending on how the app sells we might want to go cross platform and build an Android version. In this case we will only have to work on the UI side of the app while anything else will remain untouched and working out of the box.
  • the fact that with a few lines of code we could have a working proof of concept was an amazing advantage over doing mockups and then implementing them in the code.
  • we are very proficient with Appcelerator but we don’t know objC so we used what we knew best
  • we bootstrapped this so the development cost was only in hours of work and not having to pay one or more objC programmers was a real boost.
  • we developed the server in NodeJS at the same time with the app. Developing both the app and the server side in Javascript instead of JS and objC helped us keep the focus on the building proccess.

 
 

What issues did you need to overcome

At this point we’d like to get a little more technical and explain how we managed to overcome the problems we had with the app.

One issue was the amount of the XHR calls we had to make. When the app opens it fetches all the artists in the device’s music library and also basic data for each of them. As you can see in the screenshot the application is very visual, we have a lot of images and each artis will have a lot of information:

Way too many XHR calls

Our main goal was to make a very responsive app and due to the amount of server calls we had to find a balance between the information sent from the server and the number of calls. So we decided to go with many calls that return a small amount of information. The overall time the user has to wait might be bigger in this case but the app doesn’t lock and the feedback received is really fast.

We hit a wall here because the ASIHttpRequest – the objC library Titanium uses on the native side – has a limit of 4 concurrent requests. The rest of the requests are put in a queue and executed when the previous calls finish.

What ASI does is perfectly correct, there is no point in overloading the network with too may concurrent requests but in our case the user would have had to wait for ALL the images from the previous windows to load in order to be able to receive the current window information.

We modified the XHR library to be able to handle a queue and priorities and we set the images to have the lowest priority while the artist information (JSON data) has the highest priority. At the JS level we limit the simultaneous requests for the images at only 3 so we always have a free slot on the native side for the data – higher priority requests are passed to ASI immediately.

Of course we take advantage of the caching that XHR does and we have a request to the server only once: the first time a new resources is requested or when the time to live expired. This way after the initial load the number of global requests decreases drastically.

Blocking the UI

The images are diplayed in tableViewRows and if we had put the source of the image directy in the imageView the UI would have locked until the image was loaded.

What we did was create the image **but without** the source property, download the image locally and save it then populate the source with the local file URL. This way the table will scroll normally and the pictures will be loaded one by one giving the user a way better experience.

Youtube clips

We have to display lots of videoclips from Youtube which can be done in two ways:

  1. open the clip in mobile Safari or the Youtube app. This meant making the user leave ArtistBox and it was not an acceptable option.
  2. use webviews to load the clip – not a good approach as we had to keep the memory footprint as low as possible.

We came with a different approach: each time the user taps on a clip the app makes a call to the mobile version of the Youtube site, finds the streaming link and opens a videoplayer with the source URL set to this streaming link.

The disadvantage is that the user will have to wait for an extra request to the Youtube servers but the overhead is not too big. The fact that he/she can see the videoclip right inside the app makes it worth it.

There were a few more aspects we had to take care of. The first one was to show very clearly that the videos are coming from Youtube so we designed the thumbnails with the big “Youtube” watermark. We also had to filter the results within the Youtube APIs to return only the videos allowed to run on mobile and also in the user’s country.

You can download the module from Github, it is MIT licensed.

We believe that the complexity of ArtistBox pushed the Titanium framework to the limits as we are using a large number of its APIs in our app (tableViews, videoPlayer, audioPlayer, lots of imageViews, scrollableViews, httpClient, localStorage, UI transtions, webviews, etc) and not always in a common way. But we also believe that Titanium was the right choice and it reached our expectations :)

There are also a few modules we used and we want to thank their creators:

- a modified version of XHR by Raul Riera
- TiNetworkHelpers by Ben Bahrenburg
- a modified version of TiMiniBrowser by Rafael Kellermann Streit

Enough talking, let’s see some action

ArtistBoxApp from ArtistBox App on Vimeo.

ArtistBoxApp from ArtistBox App on Vimeo.

Final words

ArtistBox is a very complex application that has to deal with a huge amount of information while also being memory leaks free. Making it stable and very fast were our main purposes because the users are very sensitive when it comes to huge loading times and repeated crashes. Being able to offer them so much info about their favourite artists while displaying the UI in an instant were two very challenging tasks that we hope we completed successfully. You can see we’re not trying to be modest here, test the app for yourselves and let us know what you think.


Appcelerator Participates in NASA’s International Space Apps Challenge

Last month, NASA hosted the International Space Apps Challenge – a 48-hour hackathon that invited citizens from around the world to collaborate to create open-source solutions for problems NASA faces both in space and here on Earth. NASA released a list of more than 50 challenges for hackathon teams to tackle, including a wide range of topics such as solar flare, star maps, space stations and renewable energy. Teams could sign up to participate virtually from anywhere  in the world.

We are proud that a few teams from the Appcelerator community participated in the International Space Apps Challenge, and we are excited to showcase their work. Great job, everyone!


by Ketan Majmudar

Project: T-10 (pronounced “T-Minus Ten”)

Team (Appcelerator community):
Kate Arkless Gray @SpaceKate
João Neves @jpgneves
Ketan Majmudar @ketan
Dario Lofish @dariolofish

The Challenge: Spot the Station

NASA recently launched the Spot the Station website, which allows people to spot the space station and sign up for alerts when it flies overhead. The tasks were to:

  • “Extend the functionality of the Spot the Station site by building an app that allows you to share your sightings with others.”
  • “Create a visualization with Spot the Station data.”

The Solution:

T-10 from João Neves on Vimeo.

Overview

Our goal was to set up an alert to help astronauts on the International Space Station (ISS) take images of planet Earth under their specific desired circumstances. For example, they might want a picture of London with clear skies or a picture of New York during a thunderstorm.

The T-10 app allows astronauts to select cities of interest, time of day and the weather condition required. This data is then sent to our server, which waits for the correct conditions and finds the next scheduled times the ISS will be over the city in question. When both city and weather conditions are met, a push notice is sent to the app and provides an alert 10 minutes before the ISS will enter visibility of that city, giving astronauts enough time to prepare to take the photo.

When the T-10 countdown begins, it also sends a push alert to any ground users who have the app installed and would like to send a digital wave back to the ISS and the astronauts aboard. This two-way communication creates a social connection and sense of unity, promoting the knowledge that people on Earth and in space are waving at each other.

In future updates, we hope to add the ability to add the #ISSWave hashtag to share pictures to and from the ISS and Earth. We also intend to add more complex controls to manage when and how alerts get stored and shared with others.

Getting Started

I signed up for the International Space Apps Challenge in London, held at the Google Campus in East London. I had been invited to take part in a European space apps hack recently, but due to working commitments, I completely missed it. When I saw the announcement for the International Space Apps challenge, I signed up as quickly as I could. Being a NASA-driven event just added to the awesomeness of the hackathon. My main goal was just to participate, and I wasn’t even intending to take part seriously in the challenge aspect. I was more than happy to network and tinker with some cool ideas and people over the weekend.

A very early start on Saturday morning was a challenge in itself, having been up late every night for the past two weeks working on the SCI-FI-LONDON film festival app, but I felt it was my duty to make the effort for this hackathon. To be honest, I didn’t know what kind of people would be present or if I would have the energy to stick through a whole weekend. I went in expecting to build an app using the Patino game engine for Titanium, as I’m on the private beta – perhaps a cosmic windchime or mapping related to a comet or near-Earth object. But in the midst of the opening pitches and the multitude of available broad challenges to choose from, fate and social connections led us to form our team and the app T-10.

I tweeted Kate Arkless Gray (@SpaceKate) – whom I’d met through Bill Thompson (@billt), a technology journalist who works for the BBC Click Radio programme – and we connected with an idea to build an alerting app system which related to current earth weather patterns. Although my original idea was more Earth-bound, Kate had actually asked astronauts from the ISS if they would use an app that would tell them when the weather was good so they could take snaps of the planet! This was a cool plan, and we set it in motion.

Kate’s friend Joao Neves (@jpgneves), a software engineer and Android hacker from Stockholm, came on board, and we decided to use Titanium as the core of the application and build a server component. What I most enjoy about the Titanium platform is that it allows me to take the foundation of my learned skill sets and apply it to something amazing that is inclusive within the mobile community. Targeting multiple platforms is awesome, and being JavaScript-based, Titanium has helped me embrace the language in a way I never would have before.

The Process

We had to make sure we had the right APIs on hand and a suitable user-flow. We found a table that would be our home for the next 12 hours and had an open recruitment office in the form of stickies on the edge of our table. We sat and began coding an app that would use ACS push notifications and a bunch of open-source Titanium scripts. We had so much fun building, designing and conceptualising the app and solution that we wanted to weave a few more ideas in, knowing that we could never achieve the Flickr pool upload, share integration and Earth-based “wave” functionality that would enable people on the ground to send a virtual wave to the ISS as it flew over.

When our fourth team member, designer Dario Lofish (@dariolofish), logged on, our dream team was complete. We all connected online, made sure we were in tune with the concept and approach, then got back to our roles.

As fate would have it, the ISS was due to fly over London at around 9:30, and Kate dragged us (plus about 10 others) so we could see it fly over. Then back to the hacking. Under normal circumstances, we would have stayed all night, but by 22:30, I bailed to the far recesses of North London, promising to return the following morning.

App design during hackathons can be crazy, but we managed to have clear roles and had a simple core concept that we were all behind. Titanium made it easy to prototype ideas and integrate design ideas on the fly quickly.

Highlights & Insights

Our demo at the end of the day went really well, and I demonstrated the functionality of setting and sending the event from my iPhone 4S plugged directly into the projector, with push notification responses. It was a real joy to be part of the team behind T-10, and I’m proud of the ease and speed with which our team locked into the development process and how easy we made all of our jobs seem.

I was pleased to see a lot of mobile solutions come out of the weekend, many of them trying to take complex space data and put them into the hands of ordinary people in a way that makes sense. There were some superb, inspiring solutions that bridged the gap between software and hardware. It was also incredible to see the cooperation and coordination of people, some in the same room, some located all over the world. Since I was 10, I have had this odd dream to become a developer – back then it was just a desire to be a computer programmer. Mobile development has suddenly become a huge business and one that has moved in from the fringe of society into an evolving and ever-shifting set of features and parameters. With every year, new concepts, gestures and devices evolve and play a role in how our societies interact with the world around us. It is very cool and exciting to be part of that change.

At the end of the hackathon, we were so excited when they announced that we had been chosen by the judges as one of the two winning London Challenge teams! We are hoping that we will do well in the global round coming up and that our app will be featured in the Victoria and Albert Museum as part of the Digital Futures: Urban Open Space event.

We are now in the People’s Choice voting phase, so you can vote for T-10 via Twitter. Wish us luck!


Appcelerator Node.ACS Financial Stock Watch List

Implementing a Financial Stock Watch List may seem pretty straightforward at first, but optimizing it for mobile in the most efficient way possible presents a few challenges. Today, I’d like to walk you through how you can use the Appcelerator Mobile Platform to streamline API calls and data over the wire for your mobile applications leveraging remote data sources.

Appcelerator Custom Cloud Service (Node.ACS) allows Node.js based custom services to be published into the cloud and can be used to create a middleware tier to expose mobile-optimized web services to your application.

Instead of making multiple calls from the Titanium mobile client directly to the stock quote web service, we will create a Node.js service which will make multiple calls to a back end Stock Quote web service over the high speed internet and present aggregated data to the Titanium mobile client. The Titanium mobile client can then make a single mobile optimized web service call to Node.ACS over the slower cellular network to retrieve the Stock Watch List data. Furthermore, since the Watch List only displays 3 data values from the 13 provided by the stock quote web service, a substantial reduction in overhead is achieved which results in improved user experience and reduced data transmission.

The Problem

The mobile watch list we are trying to create is shown below:

The Stock Watch List displays a list of Stock Symbols as well as the Last Price and Change (from the prior day) for each stock symbol in the list. The “As of” time and date is useful to display as well so the user can see when the stock data was last retrieved.

The stock web service used in this example is from Markit On Demand.

In order to implement the watch list, repeated calls to a stock quote web service needs to be made; one call for each stock symbol the user is “watching”. The data then needs to be assembled and applied to a list control (i.e. TableView).

Below is an example of a stock quote REST web service call and JSON reply from MarkitOnDemand for the stock symbol AAPL (Apple Inc):

Call:

 

http://dev.markitondemand.com/Api/Quote/json?symbol=AAPL

Reply:

{
	"Data":{
		"Name":"Apple Inc", "Symbol":"AAPL", "LastPrice":424.04,
                "Change":-3.36899999999997,
		"ChangePercent":-0.788237964104632,
		"Timestamp":"Tue Jan 22 10:58:00 UTC-07:00 2012",
		"MarketCap":395266765800,
                "Volume":263809,
		"ChangeYTD":402.64,
                "ChangePercentYTD":5.31492151798133,
                "High":424.99,
		"Low":423.22,
		"Open":424.86
	}
}

From the reply above, you can see that we only need 3 of the 13 values returned by the web service for our watch list: LastPrice, Change and Timestamp. While these calls can be made from the Titanium mobile client, there is a large amount of overhead due to the unused data returned by the web service. Also, these calls are made across the often slow and unreliable cellular network as illustrated in the diagram below:

SOLUTION

One solution to this problem is to change the application architecture so that the watch list is retrieved by Appcelerator’s Node.ACS Platform as a Service (PaaS). Then the Titanium mobile client only needs to make one web service call to Node.ACS to retrieve the watch list data. The Node.ACS service makes the repeated calls to the Stock Quote web service to collect the watch list data but it does this across the high speed Internet instead of the slow cellular network as illustrated below:

The custom Node.ACS service is shown below. Note that an additional feature in this Node.ACS service is that the Watch List symbols are retrieved from ACS Custom Object. This enables watch lists to be maintained across mobile devices.

var ACS = require('acs').ACS;
var logger = require('acs').logger;
var EventEmitter = require('events').EventEmitter;
var https = require('http');
var sessionID = null;
var stocks;
ACS.init('', ''); // use your ACS OAuth key and secret

function refreshPrice(req, res) {
    var uid = req.query.uid;
    var Event = new EventEmitter;
    var results = [],
        evt_count = 0;
    // SETUP EVENT LISTENER
    Event.on("HTTP_COMPLETE", function (e) {
        console.log("EVENT: HTTP_COMPLETE");
        evt_count++;
        console.log(evt_count);
        if (evt_count >= stocks.length) {
            console.log("close response, results = " + JSON.stringify(results));
            res.write(JSON.stringify(results));
            res.end();
        }
    });
    ACS.Objects.query({
        page: 1,
        per_page: 100,
        classname: "stocks",
        where: {
            user_id: uid,
        }
    }, function (data) {
        console.log(JSON.stringify(data));
        stocks = data.stocks;
        var l = stocks.length;
        if (l == 0) {
            Event.emit("HTTP_COMPLETE");
        };
        for (var i = 0; i < l; i++) {
            marketOnDemandQuote(stocks[i].symbol);
        }
    })

    function marketOnDemandQuote(symbol) {
        var myreq =
            https.get('http://dev.markitondemand.com/Api/Quote/json?symbol=' + symbol, function (r) {
            r.setEncoding('utf8');
            r.on('data', function (chunk) {
                console.log(chunk);
                var o = {}, d = JSON.parse(chunk);
                o.symbol = d.Data.Symbol;
                o.name = d.Data.Name;
                o.lastPrice = d.Data.LastPrice;
                o.change = d.Data.Change;
                o.changePercent = d.Data.ChangePercent;
                o.timestamp = d.Data.Timestamp;
                results.push(o);
                Event.emit("HTTP_COMPLETE");
            });
        });
    }
};
exports.refreshPrice = refreshPrice;
// Source code attribution: Asim Siddiqui and Bert Grantges

Conclusion

Appcelerator’s Node.ACS Platform as a Service can be used to build mobile optimized middleware services in Node.js. The middleware service reduces the overhead in retrieving the watch list data by making repeated calls to a stock quote web service and presents the aggregated data that the mobile application needs. This results in improved user experience and reduced latency and throughput requirements of the mobile application.

While this example was designed around a stock watch list, the principles can be applied to many other use cases such as sales flash reports, key performance indicator dashboards and other applications where the back end data is not optimized for the mobile application or when data needs to be mashed up from disparate back end data sources.

The Node.ACS online documentation is a good next step for learning about Appcelerator Custom Cloud Service and can be found here: http://docs.appcelerator.com/titanium/latest/#!/guide/Node.ACS


Using ACS as a back-end for your App

On a previous post, I talked about consuming web services. Today I want to talk about ACS (Appcelerator Cloud Services), but before I go into what it is and how it can help you, let’s take a look at a scenario.

Your client asks you to build an App where people can create an account, log in and display a feed with photos that people have uploaded. Any user can then can snap a picture, upload it to the server and after being approved by an administrator let everyone else see it.

The App itself seems pretty straightforward.

  1. User login and photo feed are two API calls: you already know how to do that.
  2. Taking a picture is easy using the Ti.Media.takePicture method. Then another API call to upload.

Now the back-end, that’s another story. You need to:

  1. Find a server to host your back-end app
  2. Create the database, establish relations between tables (unless you’re using NoSQL Databases)
  3. Expose an API that returns JSON
  4. Create an admin interface
  5. Provide security
  6. Get ready to scale in case your App is very successful and you need more space or bandwidth

What if I tell you that with ACS you can do that right now, and maybe build your full App (front-end and back-end) in a day or two? In fact, let’s do it!

Setting up your app

Launch Titanium Studio and go to File > New > Mobile Project. Then select your Project Template. Now on the New Mobile Project screen, make sure you select “Cloud-enable this application”.

Studio has added for you the ti.cloud module, and has created two API Keys: One for production and one for development. What this really means is that you already have a back-end for your app!. Let’s check it out.

Go to my.appcelerator.com and click on My Apps; Login if you have to. You’ll be taken to a screen with a list of all your Apps. Locate the App you’ve just created and click on Manage ACS. You are now on your Adminstrative Console.

Using ACS

ACS has too many features to mention in a single post. If you want to know all there is to know about ACS, I’d suggest you go to http://docs.appcelerator.com/cloud/latest/. For our example we’ll be using two services: Photos and Users. To use ACS on your App, start by getting an instance to the ti.cloud module.

var Cloud = require('ti.cloud');

Your App already knows your API keys, so you’re ready to go. The ACS API follows a very simple pattern:

Cloud.Namespace.method({
     property1: 'here',
     property2: 'here'
},function(e){
     // I'm the callback.  The method will call me and the response object is in e
});

Both the properties for the method and the object that is returned are documented on the API reference. If you’d rather have a more tangible example, there’s a ACS KitchenSink at https://github.com/appcelerator-modules/ti.cloud/tree/master/commonjs/example.

User Login

For simplicity, I will not implement a way of creating a new user from the App. I’ll assume that the user is already created. To create a new user, scroll down on your ACS console, click on “Users” and then on “Create a New User”.

Fill out Email, Username, Password and Password Confirmation, and click “Submit”. Now you have a user on the system and you’re ready to login. As explained on the API documentation, and based on the simple pattern described earlier, you can call the login method sending two properties: Login (can be email or userid) and Password. Upon successful login you’ll receive an object with data for this user.

Success Example:

Error Example:

PRO TIP: On Titanium you can do console.log(JSON.stringify(your_object)) to inspect the contents of the object that was returned. Here I’m taking that response and viewing it on jsoneditoronline.org

This means that your Titanium code may look something like this:

function doLogin(e){
     Cloud.Users.login({
        login: $.uid.value,
        password: $.pwd.value
    }, function (e) {
        if (e.success) {
            var win=Alloy.createController('feed').getView();
            win.open();
        }
        else {
           alert(e.message);
        }
    });
}

The Photo Feed

To implement the Photo Feed, we use the “query” method in the Photos namespace. This method can receive many optional parameters. We’ll only use one for retrieving the results in reverse order, so we do -created_at; the minus sign reverses the order. The method will return an object will all the photos.

Example Success

As you can see, ACS has already created 6 different versions of your photo: square_75, thumb_100, small_240, medium_500, medium_640 and large_1024.

PRO TIP: Paging is supported using the “page”, “per_page”, “limit” and “skip” parameters, so implementing “lazy loading” is just a matter of writing the front-end code.

To display the feed is as simple as looping through the “photos” array. Your code may look something like this:

    Cloud.Photos.query({
        order: "-created_at"
    },function (e) {
        if (e.success) {
            if (e.photos.length == 0) {
                // no photos
                alert('There are no photos');
            }
            else {
                e.photos.forEach(function(item){
                    // work with this photo
                })
            }
        }
        else {
            alert(e);
        }
    })

Uploading Photos

To upload photos we use the “create” method, which receives the photo in binary form in a property named “photo”. You may get the photo from the photo gallery using Ti.Media.openPhotoGallery or from the camera using Ti.Media.takePicture. Once you have the photo, you may call the “create” method something like this:

     Cloud.Photos.create({
          photo : event.media
     }, function(e) {
          if(e.success) {
               // reload the feed?
          } else {
               alert(e.message);
          }
      });

So there you have it. You very own secure and scalable cloud-based back-end! I have built a proof-of-concept located at github.com/ricardoalcocer/tiphotogram. Here’s how it looks.

I’ve thrown in some bonus conditional Alloy code to use Toolbars on iOS and ActionBar on Android.

This is not a finalized app, just a quick example of you can quickly put together an Alloy-based front-end with an ACS back-end. Feel free to use, fix and improve upon it.

Final thoughts

You can use ACS with or without Titanium, so if you’re looking for a back-end for your web-based app, ACS may be what you’re looking for. For this example we used the ACS SDK for Titanium, but you could also use the native iOS or Android SDK as well as the REST API. ACS offers 20 pre-build services, one of which is Custom Objects. This means that you can create your own data-sets, with your own data structure, and automatically get a REST API to interact with them.

Page 1 of 9112345...102030...Last »