Transcript
Build Your First Mobile Flex Application Tutorial Exercises Narciso Jaramillo
2 | Build Your First Mobile Flex Application
Table of Contents Introduction ................................................................................................................. 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 ............................................................................ 10 Exercise 3. Connect the trends view to data ............................................................... 12 Exercise 4. Debug the application on the desktop ...................................................... 14 Exercise 5. Add a view to display tweets for a trend ................................................... 16 Exercise 6. Set up view navigation .............................................................................. 18 Exercise 7. Configure the list item renderer ................................................................ 20 Exercise 8. Debug the application on a device ............................................................ 23 Exercise 9. Add a view to show information for a selected user .................................. 25 Exercise 10. Set up data persistence between sessions ............................................... 30 Exercise 11. Export an application package for release ............................................... 32 Extra Credit ................................................................................................................ 34 Appendix 1. Installing the USB driver on Windows ..................................................... 35
Build Your First Mobile Flex Application | 3
Introduction Welcome to the new mobile development features in Flash Builder and Flex SDK 4.5! This tutorial is based on a lab originally created for the preview release at MAX 2010, but has been updated for the final 4.5 release. This tutorial requires the final release of Flash Builder 4.5, as well as a set of sample files packed up as TwitterTrendsAssets.zip. You can download them from the Adobe Developer Connection at: http://download.macromedia.com/pub/developer/flex/TwitterTrendsAssets.zip Within a ZIP file is an FXP file, TwitterTrendsFinal.fxp. This is a Flash Builder project file that contains the final source for the project. If you run into problems in the tutorial, you can import this file as a project using File > Import Flash Builder Project. You can then compare your code to the code in that project to see what might be wrong. If you run into problems, please post a question to the Flash Builder forum or the Flex SDK forum. Items in boxes are optional information that you can read if you want to understand more of what you’re doing. It’s not necessary to read this text to follow the steps.
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. On iOS and Blackberry Tablet OS, simply add a back button in the Action bar to handle the Back button navigation.
By default, mobile Flex applications are structured as a series of views—individual 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.
5. 6. 7. 8.
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. Apple iOS, Blackberry Tablet OS and Google Android are checked b. View-‐Based Application is selected c. Automatically reorient is checked and Fullscreen is unchecked Check "Automatically scale application for different screen densities" at the bottom, and leave Application DPI at its default value of 160 dpi. We'll discuss this option in more detail later on in this section. Click Finish. The first time you create a project, this may take awhile. Unzip the TwitterTrendsAssets.zip file provided with this tutorial. Drag the assets folder into the src folder in the Package Explorer on the left side of Flash Builder.
6 | Build Your First Mobile Flex Application Flash Builder generates two MXML components: TwitterTrends.mxml, which is the main application file, and TwitterTrendsHomeView.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 application—most 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 application 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
… tag. 3. Add the following code between the
and tags:
Add back navigation to the Action Bar for iOS and BBOS The Action Bar also supports the common iOS and BlackBerry Tablet OS back navigation. This can be added by through a combination of CSS and MXML. In this application, you can optionally add an iOS or BBOS back button. Add the following code between the
and tags: 1. Create a
block and use the @media syntax to apply specific styling
to the button while running on iOS:
@namespace s "library://ns.adobe.com/flex/spark"; @media(os-platform:"IOS") {
Build Your First Mobile Flex Application | 7 s|ActionBar { defaultButtonAppearance:beveled; } .backButton { skinClass:ClassReference("spark.skins.mobile.BeveledBackButtonSkin"); } } 2. Add the back button between the tags:
3. Add a script block to hide the back button when in Android: protected function shouldDisplayBackButton():Boolean { var notAndroid:Boolean = Capabilities.version.indexOf(‘AND’) != 0; return notAndroid; }
4. Finally, bind to this function in the includeInLayout property of the back button and the click handler to go back to the previous view:
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. Content that you add in the main application shows up in all views by default, but you can also add content to any of the Action Bar content areas in an individual view, as we'll see later. Setting one of the content areas in an individual view overrides the content from the application.
8 | Build Your First Mobile Flex 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 refresh() method on it. You'll implement this method in each of the views you'll be creating in this tutorial.
Set up a multi-‐DPI Refresh button icon In the code above, you set up an icon for the button. However, the icon might not look good on all devices because of differing pixel densities. To see this, you can look at the application in Design View. 1. In TwitterTrends.mxml, click the Design button to switch to Design mode.
2.
3. 4. 5. 6. 7. 8. 9.
Look at the refresh button icon on the right end of the Action Bar. You'll notice that it looks pixelated. This is because our application automatically scales to devices of different screen densities, as explained below. The next few steps will show you how to fix this. Click on the refresh button to select it. In the Properties view, click on the folder to the right of the Icon field and choose Multi-‐Resolution Bitmap. In the dialog, the 160 dpi asset is already filled in. Use the Browse buttons next to the other two fields to navigate into the src/assets folder and choose refresh240.png and refresh360.png, respectively. Turn on the Embed bitmaps checkbox. Click OK. Note that a smoother version of the refresh icon now appears in Design View. Switch back to Source view. You'll see that the icon is now being set using a MultiDPIBitmapSource tag. Save the file. In a desktop Flex application, you would normally just specify a single bitmap as the "icon" property of the Button component. On mobile devices, however, you have to take into account the fact that different devices have different pixel densities. For example, on a Motorola Droid Pro, the screen has 160 pixels or dots per inch (DPI), whereas on a Droid 2, the screen is 240 DPI. So, for example, a button that's 40x40 pixels is ¼-‐inch square on a 160 DPI device—just big
Build Your First Mobile Flex Application | 9 enough to target with a finger—whereas on a 240 DPI device it would only be 1/6-‐inch square, which is too small. When you set up the project in the New Flex Mobile Project wizard, you checked the box to "Automatically scale the application for different screen densities". That makes it so that the application automatically scales itself to maintain the same physical size across multiple DPIs, meaning that in general you don't have to worry about it. However, bitmaps that are scaled up become pixelated, so a single bitmap suitable for 160 DPI won't look good when scaled up on a 240 DPI or 320 DPI screen. In Design View, the default preview device is a Google Nexus One, which is at 240 DPI, so the icon scales up, leading to pixelation. The MultiDPIBitmapSource class allows you to specify bitmaps that should be used at different screen DPIs. These bitmaps will not be scaled along with the application, so they will appear at their original full resolution, leading to a crisper visual appearance. Note that because multi-‐DPI bitmaps are not scaled with the application, you need to ensure that they're sized appropriately for each DPI. In this case, the 160 DPI bitmap is 32x32, so the 240 DPI bitmap needs to be 48x48 and the 320 DPI bitmap needs to be 64x64. That makes it so that in each case, the bitmap occupies the same physical screen size.
10 | 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, TwitterTrendsHomeView.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, TwitterTrendsHomeView.mxml. 2. Click the Design button to switch to Design mode.
3. 4. 5. 6. 7. 8.
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.
Build Your First Mobile Flex Application | 11
Test the view's resizability 1. Double-‐click on the editor tab for TwitterTrendsHomeView.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 size—for example, the Motorola Droid 2. 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.
12 | 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. 1. Choose Data > Connect to HTTP… 2. Change the existing name "Operation1" to getTrends 3. Change the URL of the operation to http://api.twitter.com/1/trends.json In the Service name field, enter TwitterService and click Finish. 4. In the Data/Services panel at the bottom, bring up the context menu for getTrends() and choose Configure Return Type… 5. Make sure Auto-‐detect is selected and click Next. 6. There are no parameters to configure. Click Next again. 7. Enter Trends for the name of the data type. 8. To avoid confusion, change the type of the trends property from Trends[] to Trend[] (you don't need to type the brackets). This makes it so each trend object is called "Trend" rather than "Trends". 9. Click Finish. 10. 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. In the code, you'll see that two items were added to the tag: a TwitterTrends service object 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.
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 TwitterTrendsHomeView.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 block, add the following method: public function refresh(): void { getTrends(); }
Build Your First Mobile Flex Application | 13 2. Add viewActivate="refresh()" to the 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 tag. 2. Select Data > Bind to Data. 3. Existing call result should already be selected, and the existing CallResponder, getTrendsResult, should be selected in the dropdown. 4. For Data Provider, select the array of trends (trends[]). 5. For Label field, select name. 6. Click OK. An tag is added inside the List tag that fills the list with data from the service.
14 | 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 TwitterTrendsHomeView.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 TwitterTrendsHomeView.mxml, locate the refresh() method. 3. Double-‐click in the gray gutter to the left of the call to 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 | 15 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 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.
16 | 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 end tag:
Get the data for the TweetsView This process is similar to how you hooked up the Trends view data above. 1. Switch back to Source mode if you're not already there. 2. Change the title property of the 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. 3. In the Data/Services panel, bring up the context menu for TwitterService and choose Properties. 4. Click the Add button above the Operations table. 5. Change the existing name "Operation1" to getTweets 6. Change the URL of the operation to http://search.twitter.com/search.json 7. Click the Add button above the Parameters table twice to add two parameters. 8. Change the parameter names to q and result_type. Make sure to press the Return key after each name, and ensure the data type for each is set to "String". 9. Click Finish.
Build Your First Mobile Flex Application | 17 10. In the Data/Services panel, bring up the context menu for getTweets() and choose Configure Return Type… 11. Make sure Auto-‐detect is selected and click Next. 12. In the Enter Value column, set the q parameter to Flex and the result_type parameter to recent. 13. Click Next. 14. Enter Tweets for the name of the data type. 15. In the results property, change the type name from Results[] to Tweet[]. 16. Click Finish. 17. From the context menu for getTweets(), choose Generate Service Call. A new getTweets() function is 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 block, add the following method: public function refresh(): void { getTweets(String(data), "recent"); } 2. Add viewActivate="refresh()" to the tag at the top of the file. In this refresh method, you're passing 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 from the initial trends view.
Bind the data returned by the service into the list 1. Place your cursor between the angle brackets of the opening tag. 2. Select Data > Bind to Data. 3. Existing call result should already be selected, and the call responder getTweetsResult should be selected in the dropdown. 4. 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.
18 | Build Your First Mobile Flex Application
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 view-‐based application. 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 TwitterTrendsHomeView 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 TwitterTrendsHomeView.mxml. 2. Locate the 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:
Build Your First Mobile Flex Application | 19 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 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.
20 | Build Your First Mobile Flex Application
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 Flex SDK 4.5, we've provided an ActionScript-‐based IconItemRenderer class. Using this item renderer, you can show a label field and an optional message field below the label. 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 IconItemRenderer doesn't meet your needs, you can subclass its more general base class, LabelItemRenderer, 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 4.5 to quickly add an IconItemRenderer to the list. 1. Switch to TweetsView.mxml. (Make sure you're not in TwitterTrendsHomeView.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 tag in the List and press the Return key. 4. Type Icon (with no < before it). 5. Type Ctrl-‐Space. Because Flash Builder has a code template for IconItemRenderer (and it's the only template whose name starts with Icon), 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:
Build Your First Mobile Flex Application | 21
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 displays in bold and does not wrap by default. 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. 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. Quit ADL.
Add an icon loading placeholder and the username to each tweet 1. In the IconItemRenderer tag you created above, remove messageField="text" and replace it with messageFunction="getTweetText". 2. Add iconPlaceholder="{assets.LoadingIcon}" to the tag. (If you use Ctrl-‐Space to finish typing "LoadingIcon", it will automatically add the import statement inside the tag for you, saving you some typing in the next step.) 3. Change the IconItemRenderer tag to have a start and an end tag, and add a Script block inside it defining the getTweetText() function, as in the code below (see next page):
22 | Build Your First Mobile Flex Application
If you run the application again, you'll see the name of each user before each tweet. Also, as the icons load, you'll see a placeholder square instead of empty space. Because the placeholder square is specified as a vector graphics asset, LoadingIcon.fxg, it will scale appropriately to different DPIs automatically. However, in order to reference it in the iconPlaceholder attribute, you need to reference it as an ActionScript class rather than an embedded asset, which is why it has curly braces around it and the import statement. If you wanted to use a multi-‐DPI bitmap as a loading icon, you could do so using a similar pattern as the refresh button in the TwitterTrends.mxml file, making iconPlaceholder be a child tag of the IconItemRenderer instead of an attribute. If you're wondering why the import statement and the implementation of getTweetText() are inside the IconItemRenderer tag, rather than in the main Script block in the TweetsView.mxml file, it's because when you create an item renderer as a subcomponent using the tag, it's like a separate component definition. So the scope of functions and classes it refers to is within the tag itself, not the outer component's tag.
Build Your First Mobile Flex Application | 23
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 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 Android 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. On different devices, you might see "USB Connected" or "USB Connection", or an entry that says "Select to change USB connection type". 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. Ensure that your phone is on either a WiFi or cell network.
Set up your iOS device for running – See this link (http://help.adobe.com/en_US/flex/mobileapps/WSe4e4b720da9dedb5-‐ 2d82208b12e46a72ded-‐7ffc.html) Set up your Backberry Tablet OS device for running -‐ See this link (http://www.adobe.com/devnet/air/articles/packaging-‐air-‐apps-‐ blackberry.html)
24 | Build Your First Mobile Flex Application
Run on the device 1. In Flash Builder, click the dropdown arrow to the right of the Run icon in the Flash Builder toolbar and choose Run Configurations… 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 click the Refresh button on the Tweets view to get the latest tweets.
Hit a breakpoint on the device 1. In Flash Builder, set a breakpoint in the refresh() method of TwitterTrendsHomeView.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. 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. 4. Remove the breakpoint from the refresh() method by double-‐clicking on the blue dot. 5. Quit the app by clicking the Terminate button in the Debug toolbar. 6. Switch back to the Flash perspective using the button in the upper right corner of the Flash Builder workspace.
Build Your First Mobile Flex Application | 25
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 ViewNavigatorApplication (or, in the case of the titleContent, it just showed the title of the current view). Now you'll put an image in the navigationContent area, and replace the default titleContent with 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 Controls folder of the Components panel, drag an Image into the navigationContent area on the left side of the Action Bar. Make sure you see the navigationContent tab before you drop the item, as in the screenshot below.
4. In the Properties panel, set the image's Width and Height to 43. 5. Drag a Label into the titleContent area in the middle of the ActionBar, replacing the UserInfoView title. Again, make sure you see the titleContent tab before you drop it. 6. Click the Bold button in the Text section of the Properties panel. 7. Also in the Text section, click on the color picker (the black rectangle to the right of the font size) and change the text color to white. Your Action Bar should now look like this in Design view:
26 | Build Your First Mobile Flex Application
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.)
Build Your First Mobile Flex Application | 27
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. 7. With the List selected, in the Alphabetical view of the Properties panel, set borderVisible to true.
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. To get the user information, you'll create a new service call, but you'll use the same getTweets() service call that you created earlier in order to fetch recent tweets. 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.
28 | Build Your First Mobile Flex Application 6. Change the parameter name to screen_name. Make sure to press the Return key after typing 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. 1. Inside the block, add the following method: public function refresh(): void { getUserInfo(String(data)); getTweets("from:" + String(data), "recent"); } 2. Add viewActivate="refresh()" to the tag at the top of the file. 3. Delete title="UserInfoView" from the View tag.
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 tag. Select Data > Bind to Data. For Existing call result, select the getTweetsResult. For Data Provider, select the results[] array. For Label field, select text. Click OK. Following the example in Exercise 7, add an IconItemRenderer 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:
Build Your First Mobile Flex Application | 29
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 tag and set the source to {getUserInfoResult.lastResult.profile_image_url} 2. Set the text of the Label in the 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}
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.
30 | 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 persistence functionality in ViewNavigatorApplication to help automate this for developers. When you enable session persistence , 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 persistence 1. Switch to TwitterTrends.mxml. 2. In the tag, add the property persistNavigatorState="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. Quit ADL. 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 | 31 The session persistence feature 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.
32 | 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.
For complete instruction on how to get your provisioning profile and publish a realease build for iOS – See this link (http://help.adobe.com/en_US/flex/mobileapps/WSe4e4b720da9dedb5-‐ 2d82208b12e46a72ded-‐7ffc.html)
For complete instruction on how to get your developer certificate and publish a realease build for Blackberry Tablet OS -‐ See this link (http://www.adobe.com/devnet/air/articles/packaging-‐air-‐apps-‐ blackberry.html) 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.
Build Your First Mobile Flex Application | 33 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.
34 | Build Your First Mobile Flex Application
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 ViewNavigatorApplication, and the icon goes in the AIR XML descriptor file.) Add a menu to the user info view that pops you straight back to the home view. (Hint: add an tag with ViewMenuItem tags inside it, and use navigator.popToFirstView().) 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.
Build Your First Mobile Flex Application | 35
Appendix 1. Installing the USB driver on Windows If you are running Windows, you need to install the developer USB driver for your Android device before attempting to run or debug on the device. The 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: \utilities\drivers\android\android_winusb.inf You can update android_winusb.inf with USB drivers for Android devices not currently supported; 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 computer’s 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: /utilities/drivers/android/ 9. Follow the steps in the wizard to finish installation.
36 | Build Your First Mobile Flex Application
Adding Android USB device driver configurations If you have an Android device not listed in the android_winusb.inf file described above, update the 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: \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 HARDWARE ID . . . 7. Use the Windows Device Manager to install the device, as described in "Installing the USB Driver on Windows" 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.