Build Your First Mobile Flex Application: Lab Exercises

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

Build

Your First Mobile Flex Application


Lab Exercises
Narciso Jaramillo

2 | Build Your First Mobile Flex Application

Table of Contents
General tips .................................................................................................................3 Overview of the application .........................................................................................4 Exercise 1: Creating the project and setting up the Action Bar......................................5 Exercise 2. Lay out the Trends view..............................................................................8 Exercise 3. Connect the trends view to data ...............................................................10 Exercise 4. Debug the application on the desktop ......................................................12 Exercise 5. Add a view to display tweets for a trend...................................................14 Exercise 6. Set up view navigation..............................................................................17 Exercise 7. Configure the list item renderer................................................................19 Exercise 8. Debug the application on a device ............................................................22 Exercise 9. Add a view to show information for a selected user .................................26 Exercise 10. Set up data persistence between sessions ..............................................32 Exercise 11. Export an application package for release...............................................34 Appendix 1. Installing the USB driver on Windows.....................................................36

Build Your First Mobile Flex Application | 3

General tips
Welcome to the preview release of the new mobile development features in Flash Builder "Burrito" and Flex SDK "Hero"! Because this is a preview release, there are known bugs, performance problems, usability issues, and missing features. Items in boxes are optional information that you can read if you want to understand more of what youre doing. Its not necessary to read this text to follow the steps. This tutorial relies on a set of assets provided as TwitterTrendsAssets.zip. If you don't have these assets, you can download them from the Tutorials and Samples page on Adobe Labs at http://labs.adobe.com/technologies/flex/samples. These exercises are written to be followed in order. However, weve provided FXP project files in the TwitterTrendsAssets zip for the start of each exercise, so if you get stuck or lost in the middle of one of the exercises, you can restart from the beginning of the exercise, or skip ahead to the beginning of the next exercise. Use the FXPs in staticCheckpoints if you're using static data, or liveCheckpoints for live data. (See the note in Exercise 3 for information on static vs. live data.) To import an FXP file: 1. (Optional) Delete your existing TwitterTrends project by right-/control- clicking on the root of the project in the Package Explorer and choosing Delete. This avoids confusion with the new version you're going to import. 2. Choose File > Import 3. Expand the Flash Builder folder and select Flash Builder Project. 4. Click Next >. 5. Click the Browse button to the right of the File field, browse to the FXP, and click OK. 6. Click Finish. If all else fails, dont be afraid to ask the teachers or a TA for help! Or, if youre doing these exercises outside of the MAX lab, post a question to the Flash Builder forum or the Flex SDK forum.

4 | Build Your First Mobile Flex Application

Overview of the application


In this tutorial, you'll build a simple mobile Twitter browser. The application will show the list of trending topics on Twitter, allow the user to tap on a topic to see a list of tweets for that topic, and then allow the user to tap on a tweet to see more information on the user who posted the tweet. The user can use the Back button on the device to navigate back to previous views, and switch between portrait and landscape orientations.

By default, mobile Flex applications are structured as a series of viewsindividual screens of UI the user navigates between. Above the views sits the Action Bar, which typically contains the title of the current view and one or more controls for navigation, search, or other actions. In the example above, the first view, the Trends view, consists of a single Flex List component. In mobile applications, the List component scrolls in response to touch input. The Action Bar for this view shows the title of the view, as well as a Refresh button. The other views are structured similarly, though in the third view, the User Info view, the Action Bar has been customized to show the picture of the selected user.

Build Your First Mobile Flex Application | 5

Exercise 1: Creating the project and setting up the Action Bar


In this exercise, you'll create a mobile project in Flash Builder, and use Design mode to set up the global Action Bar for the application.

Create a Flex Mobile project and set up project assets


1. 2. 3. 4. Launch Flash Builder. Choose File > New > Flex Mobile Project. Enter TwitterTrends for the project name and click Next. On the Mobile Settings page, ensure that the following are set (as they are by default): a. Google Android is checked b. Mobile Application is selected c. Automatically reorient is checked and Fullscreen is unchecked 5. Click Finish. 6. Unzip the TwitterTrendsAssets.zip file provided with this tutorial. 7. Drag the assets, photos, and sampledata folders into the src folder in the Package Explorer on the left side of Flash Builder. Note: if you plan to work with the live Twitter API, instead of using the static sample data, you can just drag the assets folder inyou don't need the photos or sampledata folders. (There's no harm in including themthey'll just make your application larger.) See the note in Exercise 3 for more information about static vs. live data.

6 | Build Your First Mobile Flex Application Flash Builder generates two MXML components: TwitterTrends.mxml, which is the main application file, and TwitterTrendsHome.mxml, which is the first view of your application and is based on View. Note that unlike in desktop Flex, you don't typically put much UI content in the main applicationmost of your UI goes into the individual views. The one exception is the ActionBar, as we'll see next.

Add global content to the Action Bar in the main application file
The Action Bar is a special component in mobile Flex applications. It's part of the overall application, not part of each individual view. You can add items to it either in the main MobileApplication or in an individual view. In this application, you'll add a Refresh button that's available in all views. In Exercise 9, we'll show you how to customize the ActionBar in a specific view. 1. In the editor, switch to your main application file, TwitterTrends.mxml. 2. Delete the empty <fx:Declarations> </fx:Declarations> tag. 3. Add the following code between the <s:MobileApplication> and </s:MobileApplication> tags:
<s:actionContent> <s:Button id="refreshBtn" icon="@Embed(source='assets/refresh48x48.png')" click="Object(navigator.activeView).refresh()"/> </s:actionContent>

The Action Bar has three content areas: navigationContent on the left, titleContent in the middle, and actionContent on the right. By default, the title area of the Action Bar contains a text component that is bound to the title of each view, so you do not need to specify it. In this tutorial, we only set the Action Bar content in the main application, but you can set the content for any of the content areas in individual views as well in order to show content specific to that view. Setting one of the content areas in an individual view overrides the content from the application. Since we're adding the Refresh button into the global content for the Action Bar, the action it needs to take depends on whichever view is currently visible. So the click handler gets the currently active view and calls a

Build Your First Mobile Flex Application | 7 refresh() method on it. You'll implement this method in each of the views you'll be creating in this tutorial.

8 | Build Your First Mobile Flex Application

Exercise 2. Lay out the Trends view


In this exercise, you'll use Design mode to lay out the contents of the initial view, TwitterTrendsHome.mxml, which shows the list of trending topics from Twitter. You'll also test your layout in different orientations and screen sizes.

Lay out the view


1. Switch to the view file, TwitterTrendsHome.mxml. 2. Click the Design button to switch to Design mode. If the refresh button in your view appears as a broken image icon, click the green Refresh icon to the right of the Design button. In the Properties panel on the right, set the Title to Twitter Trends. From the Components panel on the left, drag a List into the main view area, underneath the Action Bar. Snap the list so it lines up exactly with the left edge of the View and its top is immediately underneath the Action Bar. Resize the empty List so it fills the whole View to the right and bottom. You may need to scroll the view to do this. In the Properties panel, scroll down to the Constraints section. Check the left, right, top and bottom checkboxes to pin the List to the edges of the View. If the values in the boxes aren't 0, change them to 0, as in the screenshot.

3. 4. 5. 6. 7. 8.

Build Your First Mobile Flex Application | 9

Test the view's resizability


1. Double-click on the editor tab for TwitterTrendsHome.mxml to hide the rest of the panels in Flash Builder. 2. In the Design view toolbar, click on the Landscape orientation button. Verify that the Action Bar and the List properly resize to the new orientation.

3. From the Device dropdown, choose a device with a different screen sizefor example, the Motorola Droid. The view should get larger horizontally and everything should resize properly. 4. Click the Portrait orientation button and double-click on the editor tab again to restore the panels.

10 | Build Your First Mobile Flex Application

Exercise 3. Connect the trends view to data


In this exercise, you'll fill the List in the trends view with the list of trending topics from Twitter. Note: When working through this tutorial, you have two choices. You can either work with real live data from the Twitter API, or you can use the static data provided with this tutorial. Note that when working with the live API, Twitter may choose to restrict the number of times you access the service in a given time period. To avoid this, we'll use the static data in the MAX lab. However, if you're going through this tutorial on your own, feel free to try the live data service.

Static data
1. Choose Data > Connect to XML 2. For the Path field, click Browse and browse to the trends.xml file in the src/sampledata folder. 3. Set the service name to TrendsService. Leave all other fields as the default and click Finish. 4. In the Data/Services panel at the bottom, bring up the context menu for getData() and choose Generate Service Call. This switches you to Source view and shows that a new getData() function was generated. 5. Rename the new getData() function in the code to getTrends(). (The function will still call getData() on the service.)

Live data
1. Choose Data > Connect to HTTP 2. Change the existing name "Operation1" to getTrends 3. Change the URL of the operation to http://search.twitter.com/trends.json 4. In the Service name field, enter TwitterService and click Finish. 5. In the Data/Services panel at the bottom, bring up the context menu for getTrends() and choose Configure Return Type 6. Make sure Auto-detect is selected and click Next. 7. There are no parameters to configure. Click Next again. 8. Enter Trends for the name of the type. 9. To avoid confusion, change the type of the trends property to Trend[] (not Trends[]). This makes it so each trend object is called "Trend" rather than "Trends". 10. Click Finish. 11. From the context menu for getTrends(), choose Generate Service Call. This switches you to Source view and shows that a new getTrends() function was generated.

Build Your First Mobile Flex Application | 11 In the code, you'll see that two items were added to the <Declarations> tag: a service object (either TwitterService or TrendsService, depending on which data you're using) and a CallResponder. The service object has methods to initiate network calls to the service. The CallResponder watches the service calls, and when they complete, sends out events to other components notifying them of the data returned by the service call. When working with static data, each XML file is accessed by a separate service with a single getData() method that returns the data. When working with HTTP services, you can choose to create multiple methods for different URLs on the same service.

Call the service when the user navigates to or refreshes the view
Recall that in the main TwitterTrends.mxml application file, the refresh button in the Action Bar was set to call a refresh() method on each view. You'll implement this method in TwitterTrendsHome.mxml to call the appropriate service call. You'll also call this method from the view's viewActivate event, which is called whenever the user navigates forward or back to the view. 1. Inside the <fx:Script> block, add the following method: public function refresh(): void { getTrends(); } 2. Add viewActivate="refresh()" to the <s:View> tag at the top of the file.

Bind the data returned by the service into the list


Now you'll make it so that whenever the service is called, the List shows the new data returned by the service. 1. Place your cursor between the angle brackets of the opening <s:List> tag. 2. Select Data > Bind to Data. 3. Existing call result should already be selected, and the existing call responder (either getDataResult or getTrendsResult) should be selected in the dropdown. 4. (Live data only) For Data Provider, select the array of trends (trends[]). 5. For Label field, select name. 6. Click OK.

12 | Build Your First Mobile Flex Application

Exercise 4. Debug the application on the desktop


The code for the trends view is now complete, so you're ready to run the application. While ultimately you will want to test on one or more real devices, during development it's convenient to quickly test the application on your computer. You'll learn how to run and debug your application on a physical device in Exercise 8.

Create a launch configuration and start debugging


To specify how Flash Builder should run your application, you need to create a launch configuration. 1. Select Run > Debug Configurations 2. Double-click on Mobile Application in the list on the left. This creates a new configuration. 3. At the top of the dialog, change the Name field to TwitterTrends Desktop. 4. In the Project field, ensure TwitterTrends is selected. 5. For Launch method, select On desktop and choose Google Nexus One as the device to simulate. 6. Click Debug. 7. If you're prompted to save TwitterTrendsHome.mxml, click OK. Your application runs on the desktop in the AIR Debug Launcher (ADL), and displays the list of Twitter trends.

Set a breakpoint
1. Switch back to Flash Builder. 2. In TwitterTrendsHome.mxml, locate the refresh() method. 3. Double-click in the gray gutter to the left of the call to getData() or getTrends() in the refresh() method. A blue dot appears in the gutter representing your breakpoint.

Test the application


1. Switch back to your application running in ADL. 2. In the Device menu in ADL, choose Rotate Right. The window should switch to landscape orientation, and the controls should resize to fit the window. 3. Use your mouse to drag and throw the list, simulating touch scrolling.

Build Your First Mobile Flex Application | 13 4. Click the refresh icon in the Action Bar. Flash Builder shows a dialog asking if you want to switch to the Flash Debug perspective. Check Remember my decision and click Yes. 5. In the Flash Debug perspective, new panels appear. The Debug panel shows the current call stack. The top of the stack is the refresh() method you stopped in. Clicking on other calls in the call stack navigates to other methods. The Variables panel shows the values of variables in the current scope as well as in the current object (this). Click the triangle next to this to see member variables and their values. The Breakpoints panel shows the breakpoints you currently have set. The Expressions panel lets you create specific expressions whose values you want to monitor whenever you're stopped. 6. In the Debug panel, click the Step into button several times. Flash Builder will step into the getData() or getTrends() method. 7. Click the Resume button and switch back to the ADL window. Your application continues running. 8. Quit ADL. 9. In the upper-right-hand corner of Flash Builder, click on the Flash button to switch back to the Flash Development perspective. You may need to resize the tab containing the perspective buttons in order to see it. You can also choose Window > Open Perspective > Flash.

10. Double-click on the breakpoint in the refresh() method to remove it.

14 | Build Your First Mobile Flex Application

Exercise 5. Add a view to display tweets for a trend


Now that the initial view is displaying the list of trends, you want to allow users to tap on a trend to see the tweets for that trend. To do this, you'll create a new view and hook it up to a search query for the trend. The process is similar to the one you followed for the trends view.

Create the TweetsView


1. 2. 3. 4. 5. 6. 7. Select File > New MXML Component. Set the Package field to views Set the Name field to TweetsView Leave the Layout as None. Ensure that the Based on field is set to spark.components.View Click Finish. Add a List that takes up the whole view. You can do this in Design mode by following the same steps as in the first part of Exercise 2, or you can simply type the following code before the </s:View> end tag: <s:List left="0" top="0" right="0" bottom="0"> </s:List>

Get the data for the TweetsView


1. Change the title property of the <s:View> tag at the top to "Tweets for {data}". In the next exercise, we'll see how the trend the user selects in the trends view is passed in as the data property of the TweetsView. 2. Similar to the trends view, create the data service for searching the tweets as follows.

Build Your First Mobile Flex Application | 15

Static data
1. Choose Data > Connect to XML 2. For the Path field, click Browse and browse to the search.xml file in the src/sampledata folder. 3. Set the service name to TweetsService. Leave all other fields as the default and click Finish. 4. In the Data/Services panel at the bottom, bring up the context menu for getData() under TweetsService (not the original TrendsService) and choose Generate Service Call. This switches you to Source view and shows that a new getData() function was generated. 5. Rename the getData() function to getTweets().

Live data
1. In the Data/Services panel, bring up the context menu for TwitterService and choose Properties. 2. Click the Add button above the Operations table. 3. Change the existing name "Operation1" to getTweets 4. Change the URL of the operation to http://search.twitter.com/search.json 5. Click the Add button above the Parameters table twice to add two parameters. 6. Change the parameter names to q and result_type. Make sure to press the Return key after each name. 7. Click Finish. 8. In the Data/Services panel, bring up the context menu for getTweets() and choose Configure Return Type 9. Make sure Auto-detect is selected and click Next. 10. In the Enter Value column, set the q parameter to Flex and the result_type parameter to recent. 11. Click Next. 12. Enter Tweets for the name of the type. 13. In the results property, change the type name from Results[] to Tweet[]. 14. Click Finish. 15. From the context menu for getTweets(), choose Generate Service Call. This switches you to Source view and shows that a new getTweets() function was generated.

Call the service when the user navigates to or refreshes the view
As in the trends view, you'll do this by implementing the refresh() method. 1. Inside the <fx:Script> block, add the following method:

16 | Build Your First Mobile Flex Application

Static data
public function refresh(): void { getTweets(); }

Live data
public function refresh(): void { getTweets(String(data), "recent"); }

2. Add viewActivate="refresh()" to the <s:View> tag at the top of the In a real application going against live data, you pass the data property of the TweetsView into the Twitter search service. In the next exercise, we'll see how this data property is passed into the TweetsView. In the static data case, there's no real backend to query from, so you don't pass any parametersyou just always get the same fake data.

Bind the data returned by the service into the list


1. Place your cursor between the angle brackets of the opening <s:List> tag. 2. Select Data > Bind to Data. 3. Existing call result should already be selected, and the call responder (either getDataResult or getTweetsResult) should be selected in the dropdown. 4. (Live data only) For Data Provider, select the results[] array. 5. For Label field, select text. 6. Click OK. The TweetsView is now set up to retrieve and display data, but the user doesn't have any way to get to it yet. You'll set up this navigation in the next exercise.

Build Your First Mobile Flex Application | 17

Exercise 6. Set up view navigation


Now that you've created the TweetsView, you need to make it so that when the user taps on a trend in the initial view, the application navigates to the TweetsView. When the user taps on an item in the List component in TwitterTrendsHome, the List dispatches a change event indicating that the selection has changed. You can handle this event to tell the ViewNavigator to push your new TweetsView onto the view stack. ViewNavigator is a component that manages a set of Views in a stack. When the application starts up, the only view in the stack is the firstView of the application. When you want to navigate to a new view, you push it onto the stack by calling pushView() on the ViewNavigator. When the user clicks the Back button on the device, the current view is automatically popped off the stack. You can also manually pop the top view from the stack by calling popView(). You don't normally need to create a ViewNavigator yourself; one is provided for you when you create a MobileApplication. Although the set of views is maintained as a stack, only one view (the currently active view) is actually in memory at a time; previous views are automatically disposed. However, the data property of each disposed view is retained, so when the user navigates back to a previous view, ViewNavigator can reinstantiate the view with the appropriate data.

Add a change handler in TwitterTrendsHome to navigate to TweetsView


You can use Flash Builder's content assist feature to easily create the change event handler. 1. Switch back to the editor for TwitterTrendsHome.mxml. 2. Locate the <s:List> tag and click immediately before the end angle- bracket of the start tag. 3. Type a space, then start typing change. A content assist popup appears showing you property and event names, with change highlighted. Press the Return key to select it from the popup. 4. Another popup appears showing Generate Event Handler selected. Press the Return key again to select it. Flash Builder gives the List the id "list" and creates a list_changeHandler method. 5. Inside the new list_changeHandler method, type the following:

18 | Build Your First Mobile Flex Application navigator.pushView(TweetsView, list.selectedItem.name); This tells the ViewNavigator to create an instance of TweetsView, and to pass it the name of the selected trend as its data property. In the previous exercise, you bound the data property into the title of the TweetsView and (if you're using the live API) used it to query the Twitter search service for tweets relevant to the trend. If you run the application now and tap on a trend in the initial view, you'll see that the tweets are shown in the list. However, you only see one line of each tweet, and you don't see the image or name of the person who posted the tweet. You'll configure this in the next exercise.

Build Your First Mobile Flex Application | 19

Exercise 7. Configure the list item renderer


As mentioned at the end of the previous exercise, you need to specify how the list should display data. In Flex, you do this by creating an item renderer for the list. In desktop Flex applications, you would normally do this by creating a custom MXML component based on ItemRenderer. However, in mobile applications, using MXML to create item renderers can cause performance problems when the list is scrolled. As a result, we recommend that you use ActionScript-based item renderers in mobile Flex applications. In "Hero", we've provided an ActionScript-based MobileIconItemRenderer class. Using this item renderer, you can show a header field and an optional message field below the header field. You can also optionally show an icon or image to the left of the text in each item, and a decorator on the right end. If MobileIconItemRenderer doesn't meet your needs, you can subclass its more general base class, MobileItemRenderer, and add and lay out your own controls in ActionScript. Showing how to do this is beyond the scope of this tutorial, but we plan to make examples available in the future.

Create a mobile item renderer


You can use the new Code Templates feature of Flash Builder "Burrito" to quickly add a MobileIconItemRenderer to the list. 1. Switch to TweetsView.mxml. (Make sure you're not in TwitterTrendsHome.mxml, which has similar List code.) 2. Delete the labelField="text" property from the List. You'll remap this text property in the item renderer below. 3. Place the cursor immediately after the end of the <s:AsyncListView/> tag in the List and press the Return key. 4. Type Mobile (with no < before it). 5. Type Ctrl-Space. Because Flash Builder has a code template for MobileIconItemRenderer (and it's the only template whose name starts with Mobile), it automatically fills out the basic structure of the code for you. 6. Fill out the item renderer code as shown on the next page:

20 | Build Your First Mobile Flex Application


<s:itemRenderer> <fx:Component> <s:MobileIconItemRenderer iconField="profile_image_url" iconWidth="80" iconHeight="80" labelField="" messageField="text" height="110" verticalAlign="top"/> </fx:Component> </s:itemRenderer>

The field properties specify which members of each data item to use as the message and icon. By using messageField instead of labelField for the text, you enable the text to wrap to multiple lines. labelField (which maps to the headerField of the item renderer) displays in bold and does not wrap by default. Note that in this preview release of "Hero", the item renderer does not automatically grow vertically if the tweet gets taller, which is why we put a fixed height on it. In the final release, the height will not be necessary since the renderer will grow to accommodate its content. 7. Click the Run button in the Flash Builder toolbar to run the application on the desktop. 8. Click on a trend in the initial view. (If using static data, click on "Inception".) This brings you to the tweets view for that trend. 9. Select Device > Back in the ADL menu (or type Ctrl/Cmd-B) to go back to the trends view. (If you don't see the ADL Device menu, switch to another application, then switch back to ADL.) 10. Quit ADL. Note that some of the tweets are not fully displayed. In the preview release, MobileIconItemRenderer does not resize to the height of its content, which is why we added an explicit height above. This will be addressed for the final release.

Add the username to each tweet


1. In the MobileIconItemRenderer tag you created above, change messageField="text" to messageFunction="getTweetText". 2. Change the MobileIconItemRenderer tag to have a start and an end tag, and add a Script block inside it, as in the code below:

Build Your First Mobile Flex Application | 21

<s:MobileIconItemRenderer iconField="profile_image_url" iconWidth="80" iconHeight="80" labelField="" messageFunction="getTweetText" height="110" verticalAlign="top"> <fx:Script> <![CDATA[ private function getTweetText(item: Object): String { return item.from_user + ": " + item.text; } ]]> </fx:Script> </s:MobileIconItemRenderer>

If you run the application again, you'll see the name of each user before each tweet.

22 | Build Your First Mobile Flex Application

Exercise 8. Debug the application on a device


Before finishing the functionality of the application, let's try running it on a physical device. You'll need a device running Android 2.2 ("Froyo") and a USB cable to connect it to your computer. If you don't have a device, skip ahead to the next exercise.

Set up your device for running


1. On the device, ensure that USB debugging is enabled: a. Tap the Home button to go to the Home screen. b. Tap the Menu button and choose Settings. c. Choose Applications, then Development. d. Ensure USB debugging is checked. 2. Connect your device to your computer with a USB cable. 3. Pull down the notification area at the top of the screen. You should see "USB Connected" or "USB Connection". a. Tap on the "USB Connected" or "USB Connection" entry. b. If a set of options comes up that includes "Charge Mode", select that mode and tap OK. c. If you see a button for turning off mass storage mode, click that button. 4. If your computer is running Windows, you need to install the appropriate USB driver for your device. See Appendix 1 at the end of this workbook. 5. Pull down the notification area at the top of the screen. "USB Debugging" should now appear as an entry in this area. If not, double-check the USB mode as in step 3 and ensure that it is not set to "PC Mode". 6. If you have an earlier preview release of AIR 2.5 for Android installed on your device, uninstall it first: a. Tap Home, then Menu, and choose Settings. b. Choose Applications, then Manage Applications. c. Choose Adobe AIR. d. Click Uninstall. 7. If you are using the live Twitter API, ensure that your phone is on either a WiFi or cell network.

Run on the device


1. In Flash Builder, click the dropdown arrow to the right of the in the Flash Builder toolbar and choose Run Configurations Run icon

Build Your First Mobile Flex Application | 23 2. In the list on the left, select your existing TwitterTrends Desktop configuration and click the Duplicate button at the top. 3. Change the Name to TwitterTrends Device. 4. Change the Launch method to On device. 5. Click Run. The first time you launch, Flash Builder will install the AIR runtime on the device, then install your application. To follow the progress of the launch, you can click on the progress icon in the very bottom right of the Flash Builder workspace, to the right of the progress bar. When the application launches on your device, you should be able to scroll the list of trends and tap on a trend to see its tweets, just as on the desktop, and use the back button on the device to navigate. You should also be able to turn the device to landscape orientation and see that everything works properly, and (if using live data) click the Refresh button on the Tweets view to get the latest tweets.

Set up your device for debugging


When debugging on a device, the AIR runtime communicates with the debugger in Flash Builder over the network. That means that your device must be connected to WiFi on a network that can access your computer via its IP address. 1. Ensure that your device is connected to WiFi: a. Tap the Home button. b. Tap the Menu button, then choose Settings. c. Choose Wireless & networks. d. Check the Wi-Fi checkbox if it's not already checked. e. Tap Wi-Fi settings. f. If you're not already connected to WiFi, tap on a network to connect to (at MAX, use the OfficialMAX2010WiFi network), 2. Make sure your laptop is connected to the same network. (At MAX, it needs to be on the same WiFi network. In other contexts, it just needs to be on a network accessible from the WiFi network your device is connected to.) 3. If you're running Windows Vista or Windows 7, you will need to temporarily disable your firewall in order to debug, due to an issue in the preview release. On Windows XP, you can open ports 7 and 7935.

24 | Build Your First Mobile Flex Application

Hit a breakpoint on the device


1. In Flash Builder, set a breakpoint in the refresh() method of TwitterTrendsHome.mxml (as you did in Exercise 4). 2. Click the dropdown to the right of the Debug button and choose TwitterTrends Device. The Twitter Trends app running on your phone should quit and restart in debug mode. 3. If you see an IP address dialog on your device when the application restarts, the debugger was unable to connect to your computer. See the notes in the "Set up your device for debugging" section above, or (in the lab) ask a TA for help. 4. When the application starts, you should hit the breakpoint (since it gets called on activation of the initial view). You can access all the debugging capabilities of Flash Builder on device, just as you did on the desktop in Exercise 4. Note, however, that some operations, like stepping into functions or drilling down into the contents of an object in the Variables view, may be slower when debugging on a device. If your application doesn't seem to be able to connect to the debugger, your network connection may be improperly configured. For example, if your computer is on a VPN network and the phone is not, disconnect the computer from VPN before attempting to debug. Consult the Flash Builder documentation (or, in the lab, ask a TA) for more troubleshooting help. 5. Remove the breakpoint from the refresh() method by double-clicking on the blue dot.

Build Your First Mobile Flex Application | 25

Extra Credit Exercises


(Skip ahead to Exercise 11 to see how to package up the final application for deployment.)

26 | Build Your First Mobile Flex Application

Exercise 9. Add a view to show information for a selected user


Now we'll complete the functionality of the application by adding a view to show the information about the user who posted a given tweet. This view has a slightly more complex layout than the previous views: the Action Bar is customized to show the image and name of the selected user, and the view content has some labels to show the location and website of the user, along with a list of the user's recent tweets.

Create the view and customize its Action Bar


In the previous views, you didn't change the Action Bar, so it just showed the content from the MobileApplication (or, in the case of the titleContent, it just showed the title of the current view). Now you'll replace the default titleContent with an image and the name of the user who posted the tweet. 1. As you did with the TweetsView, use File > New MXML Component to create a new View called UserInfoView in the views package. 2. Switch to Design mode. 3. From the Layout folder of the Components panel, drag a Spacer into the titleContent area of the Action Bar. This will replace the default titleContent, so you'll see it disappear.

4. In the Properties panel, set the Width property to 15. 5. Drag an Image into the titleContent to the right of the Spacer and set its Width and Height to 60. (Note: due to an issue in the preview release, the titleContent container box may not look correct when you do this.) 6. Drag another Spacer to the right of the Image and set its Width to 15. 7. Drag a Label to the right of the Spacer. 8. Click the Bold button in the Properties panel.

Your Action Bar should now look like this in Design view:

Build Your First Mobile Flex Application | 27

Lay out the view content


1. From the Components panel, drag out four Labels and arrange them as shown below.

2. Double-click each label to set the text as in the screenshot above. The labels on the right have placeholder content for now; you'll data-bind them later. 3. Select the labels on the left and click the Bold button in the Properties panel. 4. Select the "(location)" label on the right, and: a. Resize the right edge of the label to near the right edge of the view, leaving some padding.

b. In the Constraints section of the Properties panel, pin it to the left and right edges, as in the screenshot on the next page. (The number on the left may not be exactly the same.)

28 | Build Your First Mobile Flex Application

c. Switch to the Alphabetical view of the Properties panel and set maxDisplayedLines to 1. d. Switch back to the Standard view of the Properties panel. 5. Repeat step 4 for the "(url)" label on the right. 6. Drag in a List below the labels. Move and resize it so that it's flush against the left, right, and bottom sides of the view, and constrain it to all four sides.

Get the data for the view


In this view, there are two sets of data you need to get from different services. The first is the user's profile information; this is used to fill the Image in the Action Bar and the location/website below that. The second is the user's recent tweets, which will fill the List at the bottom. In the static data case, you'll use two new static data files, one for the user information, and one for the recent tweets. In the live data case, you'll access a new service call for the user information, but you'll use the same getTweets() service call that you created earlier in order to fetch recent tweets.

Build Your First Mobile Flex Application | 29

Static data
1. Choose Data > Connect to XML 2. For the Path field, click Browse and browse to the userinfo.xml file in the src/sampledata folder. 3. Set the service name to UserInfoService. Leave all other fields as the default and click Finish. 4. In the Data/Services panel at the bottom, bring up the context menu for getData() under UserInfoService and choose Generate Service Call. This switches you to Source view and shows that a new getData() function was generated. 5. Rename the getData() function to getUserInfo(). 6. Right-click/Ctrl-click on getDataResult and choose Refactor > Rename 7. Change the name to getUserInfoResult and click OK. This modifies the name in both places where it's used. 8. Follow steps 1-7 for searchUserTweets.xml, naming the service UserTweetsService. Rename the new getData() function to getTweets() and use Refactor > Rename to change getDataResult to getTweetsResult.

Live data
1. In the Data/Services panel, bring up the context menu for TwitterService and choose Properties. 2. Click the Add button above the Operations table. 3. Change the existing name "Operation1" to getUserInfo 4. Change the URL of the operation to http://api.twitter.com/1/users/show.xml 5. Click the Add button above the Parameters table. 6. Change the parameter name to screen_name. Make sure to press the Return key after the parameter name. 7. Click Finish. 8. In the Data/Services panel, bring up the context menu for getUserInfo() and choose Configure Return Type 9. Make sure Auto-detect is selected and click Next. 10. In the Enter Value column, set the screen_name parameter to Adobe. 11. Click Next. 12. The type should be prefilled as User by default. Click Finish. 13. From the context menu for the getUserInfo() method, choose Generate Service Call. This switches you to Source view and shows that a new getUserInfo() function was generated. 14. Generate another service call for the existing getTweets() method. You'll use this service call to search for the tweets from the given user.

Call the service when the user navigates to or refreshes the view
As in the trends view, you'll do this by implementing the refresh() method. 3. Inside the <fx:Script> block, add the following method:

30 | Build Your First Mobile Flex Application

Static data
public function refresh(): void { getUserInfo(); getTweets(); }

Live data
public function refresh(): void { getUserInfo(String(data)); getTweets("from:" + String(data), "recent"); }

4. Add viewActivate="refresh()" to the <s:View> tag at the top of the file.

Bind the data returned by the service into the UI


1. 2. 3. 4. 5. 6. 7. Place your cursor between the angle brackets of the opening <s:List> tag. Select Data > Bind to Data. For Existing call result, select the getTweetsResult. (Live data only) For Data Provider, select the results[] array. For Label field, select text. Click OK. Following the example in Exercise 7, add a MobileIconItemRenderer that gets the text as the messageField of the item renderer to text and sets the labelField to blank. (You don't need to specify an icon or add the user name, since all the tweets are from the same user.) The resulting item renderer code should look like this:
<s:MobileIconItemRenderer labelField="" messageField="text" height="110" verticalAlign="top"/>

In the next few steps, you'll manually type the code to bind the rest of the UI elements to data. 1. Locate the Image in the <s:titleContent> tag and set the source to {getUserInfoResult.lastResult.profile_image_url} 2. Set the text of the Label in the <titleContent> to {data}. Later we'll pass the screen name of the selected user into this view as its data. 3. For the (location) placeholder label, change the text property to {getUserInfoResult.lastResult.location} 4. For the (website) placeholder label, change the text property to {getUserInfoResult.lastResult.url}

Build Your First Mobile Flex Application | 31

Add a change handler in TweetsView to navigate to UserInfoView


1. Switch back to the editor for TweetsView.mxml. 2. As you did before, use Content Assist to generate a change handler for the List tag. This should add id="list" to the List tag. 3. Inside the new list_changeHandler method, type the following: navigator.pushView(UserInfoView, list.selectedItem.from_user); You should now be able to run the application, tap on a trend, and then from a tweet, navigate to the info for the user who posted that tweet. (In the static data case, tap on the first tweet in the tweets view to navigate to the data for that user.)

32 | Build Your First Mobile Flex Application

Exercise 10. Set up data persistence between sessions


When running a desktop application, users explicitly choose to quit the application when they're done with it. On many mobile operating systems, however, users don't typically explicitly quit applications. On Android, for example, when the user presses the Home button or presses the Back button on the initial screen of an application, the application doesn't quit; it's merely sent to the background. Conversely, when many applications are running, the operating system will terminate background applications without notifying the user. This means that mobile applications must take care of saving and restoring their state, so that when the user re-enters the application, no work is lost. Flex provides session caching functionality in MobileApplication to help automate this for developers. When you enable session caching, the application automatically saves its view stack state and view data to persistent storage on the device whenever it exits, and restores it when the application is restarted.

Enable session caching


1. Switch to TwitterTrends.mxml. 2. In the <s:MobileApplication> tag, add the property sessionCachingEnabled="true". That's all you need to do to turn on session caching! In this application, session caching is simple because the data property of each view is a simple string. In more complex applications, you may need to register data type classes with the persistence manager, or implement your own serialization for specific data types.

Test session caching on the desktop


1. 2. 3. 4. 5. 6. Click the dropdown arrow to the right of the Run button. Choose TwitterTrends Desktop. Tap on a trend to navigate to the TweetsView. Tap on a tweet to navigate to the UserInfoView. Close the ADL window. Run the application again. The application restarts on the UserInfoView, showing the user you were looking at when you quit the application. 7. In ADL, choose Device > Back (or type Ctrl-B/Cmd-B). The application navigates back to the list of tweets for the trend you were viewing in the previous session.

Build Your First Mobile Flex Application | 33 The session caching maintains the entire history of the view stack as well as the appropriate data. From the user's point of view, it looks like the application was never interrupted. You can test this on device as well, but you'll need to manually kill the application in order to test it. On Android, you can do this from the Settings > Applications > Manage Applications screen.

Clear application data when running it


When testing an application with session caching, you may want to clear the application's data when you run it in order to test a clean startup. 1. 2. 3. 4. Select Run > Run Configurations From the list on the left, choose TwitterTrends Desktop. At the bottom, check Clear application data on each launch. Click Run.

This time, the application restarts from the initial trends view. To go back to preserving session state again, go back to the launch configuration dialog and uncheck Clear application data on each launch. This checkbox also works in device-based launch configurations.

34 | Build Your First Mobile Flex Application

Exercise 11. Export an application package for release


Now that your application is complete, you may want to give it to others, or sell it in an application store. To do this, you use Flash Builder's Export Release Build dialog, which has been extended to package mobile projects. 1. 2. 3. 4. 5. Select Project > Export Release Build Ensure that your TwitterTrends project is selected in the first dropdown. For convenience, ensure that your device is connected if you have one. Click Next. Flash Builder performs an initial build of the project. In the next screen, for the Certificate field, click Create to create an unofficial self-signed certificate. 6. Enter your name as the Publisher name. 7. Enter a password in the Password and Confirm password fields. 8. Click the Browse button and specify a location and filename for the certificate. 9. Click OK. 10. Click Finish on the Export Release Build dialog. If no device is connected, you will be notified that the build was not installed on any devices. The release build is now saved as TwitterTrends.apk in the root of your project, and if you device is connected, the release build is now installed on your device. Note that the debug version of the application (which was installed when you previously debugged or ran the application on your device) is called TwitterTrends-debug; the release version is just called TwitterTrends. Before deploying an application for public distribution (through a website or through an application store like the Android Market), you will need to get an official certificate from a certificate provider, and use it to create your release build.

Build Your First Mobile Flex Application | 35

Extra Extra Credit


Congratulations! You've built your first mobile Flex application. If you're already familiar with Flex, ran through this tutorial quickly and are ready to try something more challenging on your own, here are some things to try. (You'll want to use the live API data for these.) Add a splash screen and application icon for the app. (Hint: the splash screen goes on MobileApplication, and the icon goes in the AIR XML descriptor file.) Make the URL on the UserInfoView link to the user's web page. (Hint: there's no link control, but you can style it to look like a link, handle the click event, and use Flash's navigateToURL() method.) Add a way to search for tweets with a given keyword. (Hint: you can put a TextInput control in the titleContent of the Action Bar.) Add a way to log in to Twitter and get your Twitter stream. Add a view that lets you post a tweet once you're logged in.

For more tutorials and examples, visit the Flex and Flash Builder Mobile Development page on Adobe Labs.

36 | Build Your First Mobile Flex Application

Appendix 1. Installing the USB driver on Windows


If you are running Windows, you need to install the developer USB driver for your device before attempting to run or debug on the device. The following devices are currently supported by the driver provided with Flash Builder: Google Nexus One Motorola Droid Motorola Droid 2 Motorola Droid X HTC Droid Incredible HTC Evo 4G

These device driver configurations are listed in android_winusb.inf. Windows Device Manager accesses this file when installing the device driver. Flash Builder installs android_winusb.inf at the following location: <Adobe Flash Builder Burrito Home>\utilities\drivers\android\android_winusb.inf You can update android_winusb.inf wth USB drivers for Android devices not listed above; see the next section. To install the USB device driver for an Android device, follow these steps. (Note that these steps may be slightly different on different versions of Windows.) 1. Ensure that USB debugging is turned on on your device, and that your device is in "Charge Only" mode with mass storage turned off, as described in Exercise 8 above. 2. Connect your Android device to your computers USB port. 3. If a message bubble pops up indicating that the device driver can't be found, close it. 4. Go to Control Panel and bring up Device Manager. 5. Locate the entry for your device. It should have the name of your device's manufacturer and a reference to "ADB". It will also likely have a warning icon on it, indicating that the driver is not properly installed. 6. Right-click on the item and choose "Update Driver Software". 7. Choose to manually browse to the driver. 8. Browse to this folder in the Flash Builder installation folder: <Flash Builder>/utilities/drivers/android/ 9. Follow the steps in the wizard to finish installation.

Build Your First Mobile Flex Application | 37

Adding Android USB device driver configurations


If you have a supported Android device not listed in the table above, update the android_winusb.inf file to include the device. 1. Plug the device into a USB port of your computer. Windows informs you that it cannot find the driver. 2. Using the Windows Device Manager, open the Details Tab of the device properties. 3. Select the Hardware IDs property to view the hardware ID. 4. Open android_winusb.inf in a text editor. android_winusb.inf can be found at the following location: <Flash Builder>\utilities\drivers\android\android_winusb.inf 5. Note the listings in the [Google.NTx86] section of the file. The listings contain a descriptive comment and one or more lines that includes the hardware ID. An excerpt appears below: . . . [Google.NTx86] ; HTC Dream %CompositeAdbInterface% = USB_Install, USB\VID_0BB4&PID_0C02&MI_01 . . . 6. From the [Google.NTx86] section of the file, copy and paste a comment and hardware listing. For the device driver you want to add, edit the listing as follows: For the comment, specify the name of the device. Replace the hardware ID with the hardware ID identified in Step 3 above. For example: . . . [Google.NTx86] ; NEW ANDROID DEVICE %CompositeAdbInterface% = USB_Install, NEW HARDWARD ID . . . 7. Use the Windows Device Manager to install the device, as described in Installing USB device drivers for Android devices above. During the installation, Windows provides a warning that the driver is from an unknown publisher. However, the driver allows Flash Builder to access your device.

You might also like