Download Task for this week

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
# COMP5047 – Android Lab/Studio Sessions (Week 5):
# Lab 1: Eclipse and the Android Device Emulator:
The main goal of Lab 1 is to 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 at: http://developer.android.com/resources/tutorials/hello-world.html).
1. Load up Eclipse:
 From the Windows task bar, click “Eclipse v3.7 Indigo”. You should see Eclipse 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:\eclipse\workspace.
Note: It is possible that 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 (you can browse to
the directory, which should be the following):
 C:\android-sdk-windows.
o 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 an Android Virtual Device (AVD) has 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.
Build Target: The "Build Target" is the platform target that your application will be
compiled against. Select Google APIs Platform=1.6 API level=4 from the available options.
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.sydney.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: 4
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 "4" as the API Level will
1
o
select the Android 1.6 target). With each new version of the Android system image and
Android SDK, there have 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 are
allowed to be run. If an application requires an API Level that is higher than the level
supported by the device, the application will not be installed.
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.
Notice that the "Build Target" you've selected uses the Android 1.6 platform. This means
that your application will be compiled against the Android 1.6 platform library. Android
applications are forward-compatible, so an application built against the 1.6 platform
library will run normally on the 2.2 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 (you
may need to close the Eclipse “welcome” page first if you have not already done so). Open the
HelloAndroid.java file, located inside HelloAndroid/src/au.edu.sydney.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
2
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” and then wait till the AVD begins to load.
The Eclipse ADT will automatically create a new run configuration for your project and the
Android Emulator will automatically launch. Once the emulator has loaded, unlock the emulator
by sliding the lock icon to the right, and then wait till your application appears. 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 simpler 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 (i.e. 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.
3
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.

In the Eclipse Package Explorer, expand the /res/layout/ folder and open main.xml. Once opened,
you will 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 the contained elements
should be organised in. 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
into your application, because it makes the localization of your application to other
languages simpler, without needing to hard-code changes to the layout file.

Inside the res/values/ folder, open strings.xml and click the “strings.xml” tab. 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 now created a
launch configuration, all you need to do is click the green arrow icon and select the HelloAndroid
option to run.
4
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).

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.sydney.helloandroid"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />
<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>
</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 automatically created index to all of the resources defined in the file. This class is
used by the Android SDK as a 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.sydney.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;
5
o.toString();
setContentView(R.layout.main);
}
}

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 (i.e. located at the top right in Eclipse):
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.
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.
6
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.zip” file to your Eclipse workspace.
o URL: http://sydney.edu.au/it/~wasinger/teaching/comp5047/
 In Eclipse, click File > Import…
o Select “General > Existing Projects into Workspace”.
o Select root directory: Browse to the directory that you copied the project directory to,
e.g. U:\eclipse\workspace\COMP5047 Property Application.
o Make sure the Project is listed and selected in the “Projects” list.
o Click Finish.
 Right-click the project, and click “Properties” to check:
o Android: To familiarise yourself with the listed Project Build Target.
 Right-click the project, and click “Run As” > “Run Configurations” to familiarise yourself with
creating customised Launch Configurations:
o Click the New Launch Configuration button (top left).
o Give it a Name (e.g. “COMP5047 PropertyApp”) and then select “Browse …” to open the
project that the launch configuration refers to.
o Select Apply, and then Run.
Note: You should see a black screen with the application title “COMP5047 Property
Application”. In the week 6 lab, it will be your job to finish the Property Application 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 SDK.
 Within Windows Explorer, create a directory on your home drive called U:\eclipse\sampleapps\,
and copy across a number of the Android samples from the appropriate samples directory for
the installed AVD, i.e.:
o C:\android-sdk-windows\samples\android-8\ (e.g. consider the samples LunarLander,
JetBoy, and Snake).
 In Eclipse, click File > New > Android Project.
 Tick “Create project from existing source", select the location, e.g. "U:\eclipse\sampleapps\
LunarLander", and the Build Target (e.g. Android 2.2). Click Finish.
 Run as normal, by right-clicking the open project, and selecting “Run As” > “Android Application”.
7