# COMP5047 – Android Lab/Studio Sessions (Week 4):

# Lab 1: Eclipse and the Android Device Emulator:
The main goal of Lab...
are allowed to be run. If an application requires an API Level that is higher than the level
               supported by t...
The Eclipse ADT will automatically create a new run configuration for your project and the
        Android Emulator will a...
   In the Eclipse Package Explorer, expand the /res/layout/ folder and open main.xml (once opened,
        you might need...
   In the Eclipse Package Explorer, open AndroidManifest.xml. The contents should look as follows.
        Note that the ...
   This change simply introduces a NullPointerException into your code. Run your application again.
            You shoul...
o   Select “Existing Projects into Workspace”.
                o   Select root directory: Browse to the directory that you...
Upcoming SlideShare
Loading in...5

COMP5047 Android Labs - Week 4 Task Sheet


Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

COMP5047 Android Labs - Week 4 Task Sheet

  1. 1. # COMP5047 – Android Lab/Studio Sessions (Week 4): # Lab 1: Eclipse and the Android Device Emulator: The main goal of Lab 1 is top familiarise yourself with the Eclipse IDE and use of the Android plug-in, including the Android Device Emulator (ADE). Instructions for this lab are as follows: Part 1: Creation of a new HelloWorld Android project and the running of the application in the emulator (based on the Android tutorial found at: http://developer.android.com/guide/tutorials/hello-world.html). 1. Load up Eclipse:  From the Windows task bar, click eclipse 3.4. You should see Eclipse 3.4 (Ganymede) loading up.  Select a workspace. o As all personal data on C: is deleted upon logging out of the computer, you should make certain that you select a directory on your home drive, such as:  U:eclipseworkspace. Note: It is likely you will have to remind Eclipse of the whereabouts of this directory each time you log back into one of the University computers.  Set up the location of the Android SDK: o Click Window > Preferences > Android, and fill in the SDK location:  C:android-sdk_windows_1.5_r2. Click Apply and then OK. Note: This setting is remembered by Eclipse each time you log back into one of the University computers. Also note that 3 Android Virtual Devices (AVDs) have already been created for your use. AVDs represent the emulators that you will use when running your Android applications. 2. Create a New Android Project:  From Eclipse, select File > New > Project.  Select “Android/Android Project” and click Next.  Fill in the project details with the following values: o Project name: HelloAndroid This is the Eclipse Project name, i.e. the name of the directory that will contain the project files. o Application name: Hello, Android This is the human-readable title for your application, and the name that will appear for the application on the Android device. o Package name: au.edu.usyd.it.helloandroid This is the package namespace (following the same rules as for packages in the Java programming language) that you want all your source code to reside under. o Create Activity: HelloAndroid This is the name for the class stub that will be generated by the plug-in. This will be a subclass of Android's Activity class. An Activity is simply a class that can run and do work. As the checkbox suggests, this is optional, but an Activity is almost always used as the basis for an application. o Min SDK Version: 2 This value specifies the minimum API Level required by your application. If the API Level entered here matches the API Level provided by one of the available targets, then that Build Target will be automatically selected (in this case, entering "2" as the API Level will select the Android 1.1 target). With each new version of the Android system image and Android SDK, there have likely been additions or changes made to the APIs. When this occurs, a new API Level is assigned to the system image to regulate which applications 1
  2. 2. are allowed to be run. If an application requires an API Level that is higher than the level supported by the device, then the application will not be installed. o Other fields: The checkbox for "Use default location" allows you to change the location on disk where the project's files will be generated and stored. "Build Target" is the platform target that your application will be compiled against (this should be selected automatically, based on your Min SDK Version). Notice that the "Build Target" you've selected uses the Android 1.1 platform. This means that your application will be compiled against the Android 1.1 platform library. Android applications are forward-compatible, so an application built against the 1.1 platform library will run normally on the 1.5 platform. The reverse is however not true.  Click Finish.  Your Android project is now ready. It should be visible in the Package Explorer on the left. Open the HelloAndroid.java file, located inside HelloAndroid/src/au.edu.usyd.it.helloandroid). Notice that the class is based on the Activity class. An Activity is a single application entity that is used to perform actions. An application may have many separate activities, but the user interacts with them one at a time. The onCreate() method will be called by the Android system when your Activity starts — it is where you should perform all initialization and UI setup. An activity is not required to have a user interface, but usually will. 3. Run the Application: The Eclipse plug-in makes it very easy to run your applications:  Right click the HelloAndroid project in the Package Explorer and Select “Run As” > "Android Application". Note: It is possible that you see an error in the Console. Click the Problems tab to see the error. Usually, this can be solved by clicking the project in the Package Explorer, and then F5 to refresh the project. 2
  3. 3. The Eclipse ADT will automatically create a new run configuration for your project and the Android Emulator will automatically launch. Once the emulator is booted up, your application will appear after a moment. You should now see something like this: The "Hello, Android" you see in the grey bar is actually the application title. The Eclipse plug-in creates this automatically (the string is defined in the res/values/strings.xml file and referenced by your AndroidManifest.xml file). The text below the title is the actual text that you have created in the TextView object. Note: It is best not to turn off the emulator; this will save time when it comes to recompiling and running your applications. 4. Constructing the User Interface using an XML Layout: The general structure of an Android XML layout file is simple: it's a tree of XML elements, wherein each node is the name of a View class (this example, however, is just one View element). You can use the name of any class that extends View as an element in your XML layouts, including custom View classes you define in your own code. This structure makes it very easy to quickly build up UIs, using a more simple structure and syntax than you would use in a programmatic layout. This model is inspired by the web development model, wherein you can separate the presentation of your application (its UI) from the application logic used to fetch and fill in data. XML layout files belong in the HelloAndroid/res/layout/ directory of your project. The "res" is short for "resources" and the directory contains all the non-code assets that your application requires. In addition to layout files, resources also include assets such as images, sounds, and localized strings. The Eclipse plug-in automatically creates one of these layout files for you: main.xml. You should almost always define your layout in an XML file instead of in your code. 3
  4. 4.  In the Eclipse Package Explorer, expand the /res/layout/ folder and open main.xml (once opened, you might need to click the "main.xml" tab at the bottom of the window to see the XML source). The contents should look as follows: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout> In the above example, there are two elements: LinearLayout and TextView. Here is a summary of what the attributes mean: o xmlns:android: This is an XML namespace declaration that tells the Android tools that you are going to refer to common attributes defined in the Android namespace. The outermost tag in every Android layout file must have this attribute. o Android:orientation: This attribute defines which direction contained elements should be organised. Possible values include “vertical” and “horizontal”. o android:layout_width: This attribute defines how much of the available width on the screen this View should consume. The value “fill_parent” means that the widget should fill up all available space in its enclosing container, after all other widgets are taken care of. An alternative, “wrap_content” means that the widget should fill up its natural space, unless that is too big, in which case Android can use word-wrap as needed to make it fit. o android:layout_height: This is just like android:layout_width, except that it refers to the available screen height. o android:text: This sets the text that the TextView should display. In this example, you use a string resource instead of a hard-coded string value. The hello string is defined in the res/values/strings.xml file. This is the recommended practice for inserting strings to your application, because it makes the localization of your application to other languages graceful, without needing to hard-code changes to the layout file.  Inside the res/values/ folder, open strings.xml. This is where you can save all default text strings for your user interface. When using Eclipse, the ADT will have started you with two strings, “hello” and “app_name”. The contents should look as follows: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello World, HelloAndroid!</string> <string name="app_name">Hello, Android</string> </resources>  Revise the “hello” attribute value to something else. Perhaps "Hello Android. I am a string resource!" Save the file and then re-run your application. Because you have created a launch configuration, all you need to do is click the green arrow icon and select the HelloAndroid option to run. 5. The AndroidManifest: AndroidManifest.xml is the foundation of any Android application. It is in this file that you declare what is inside your application - the activities, the services, and so on. You also indicate how these pieces attach themselves to the overall Android system; for example, you indicate which activity (or activities) should appear on the device's main menu (a.k.a., launcher). 4
  5. 5.  In the Eclipse Package Explorer, open AndroidManifest.xml. The contents should look as follows. Note that the intent-filter element is used to indicate that the HelloAndroid activity is the main activity and the one to be launched when an application starts up. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="au.edu.usyd.it.helloandroid" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".HelloAndroid" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-sdk android:minSdkVersion="2" /> </manifest> 6. The R class:  In Eclipse, open the file named R.java (in the gen/ [Generated Java Files] folder). A project's R.java file is an index into all the resources defined in the file. You use this class in your source code as a sort of short-hand way to refer to resources you've included in your project. This is particularly powerful with the code-completion features of IDEs like Eclipse because it lets you quickly and interactively locate the specific reference you are looking for. For now, notice the inner class named "layout", and its member field "main". The Eclipse plug-in noticed the XML layout file named main.xml and generated a class for it here. As you add other resources to your project (such as strings in the res/values/string.xml file or drawables inside the res/drawable/ direcory) you'll see R.java change to keep up. You should never edit this file by hand. 7. Debugging your project:  The Android Plug-in for Eclipse also has excellent integration with the Eclipse debugger. To demonstrate this, introduce a bug into your code. Change your HelloAndroid.java source code to look like this: package au.edu.usyd.it.helloandroid; import android.app.Activity; import android.os.Bundle; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Object o = null; o.toString(); setContentView(R.layout.main); } } 5
  6. 6.  This change simply introduces a NullPointerException into your code. Run your application again. You should now see an error message in the emulator: Press "Force Close" to terminate the application in the emulator window.  To find out more about the error, set a breakpoint in your source code on the line Object o = null; (double-click on the marker bar next to the source code line). Then select Run > Debug History > HelloAndroid from the menu to enter debug mode. Your app will restart in the emulator, but this time it will suspend when it reaches the breakpoint you set. You can then step through the code in Eclipse's Debug Perspective, just as you would in any other IDE. Part 2: Familiarisation with the Eclipse IDE. Make sure that you have familiarised yourself with the following:  In the Java Perspective: o The Package Explorer Window, which shows the project’s structure. Also explore the project directories to see what was automatically created upon creating the project. o The Problems tab, which shows Errors and Warning for all open projects. o CTRL+F11: Loads up the last loaded application (compilation is automatic). o CTRL+H: Shortcut to file searching. o F5: Refreshes the content of the selected element with the local file system. When launched from no specific selection, this command refreshes all projects.  In the DDMS perspective (note: you may need to click the “Open Perspective” icon in the top right tab to get to the DDMS perspective): o The LogCat tab, which shows debugging information that has been coded into an application, e.g. Log.d(“The classes name”, “The debugging message.”);  The following Eclipse settings may also come in handy: o Setting project launch configurations. This allows one to change the Run configurations:  Right click a project > Run As > Run Configurations > New Launch Configuration. o Fixing project properties. This is sometimes needed when importing a project:  Right click a project > Android Tools > Fix Project Properties. o Reset perspective (e.g. Java, DDMS, Debug):  Window > Reset Perspective. o "Always launch the previously launched application"  Window > Preferences > Run/Debug > Launching. Part 3: Familiarisation with the Android Device Emulator (ADE). Make sure that you are familiar with the following:  The Applications tab  The Menu button  The Back button.  Also feel free to try out the applications on the emulator and look at the different settings that one can make. NB: Once the emulator has loaded up, don’t close it down, i.e. only exit the application not the emulator. This will save you lots of time when re-running a project. Part 4: Importing the sample property project into Eclipse, in preparation for the next lab’s GUI design and Activity & Intent coding exercises.  Using your web browser and Windows Explorer, download and unzip the “COMP5047 Property Application (Week 5 Lab).zip” file to your Eclipse workspace. o URL: http://www.it.usyd.edu.au/~wasinger/teaching/comp5047/ o In Eclipse, click File > Import… 6
  7. 7. o Select “Existing Projects into Workspace”. o Select root directory: Browse to the directory that you copied the project directory to, e.g. U:eclipseworkspaceCOMP5047 Property Application. o Make sure the Project is listed and selected in the “Projects” list. o Click Finish. o Right-click the project, and click “Properties” to check:  Android: To familiarise yourself with the listed Project Build Targets. o Right-click the project, and click “Run As” > “Run Configurations” to familiarise yourself with creating customised Launch Configurations:  Click the New Launch Configuration button (top left).  Give it a Name (e.g. “COMP5047 PropertyApp”) and then select (i.e. Browse to) which of the open projects the launch configuration refers to.  Select Apply, and then Run. Note: You should see a black screen with the application title “COMP5047 Property Application”. In the week 5 lab, it will be your job to finish the Property Application off so that it resembles something like the screen shots showed during the lecture. Part 5 (Time permitting): Try out some of the code samples that come with the Android 1.5 SDK. The code samples are found under the “<sdk>/platforms/android-<version>/samples/” directory.  To try out the samples, click File > New > Android Project.  Tick “Create project from existing source", and select the location, e.g. "C:Compilersandroid- sdk-windows-1.5_r2platformsandroid-1.5samplesLunarLander".  Run as normal, by right-clicking the open project, and selecting “Run As” > “Android Application”. 7