A brief introduction to Android Basics and Java
A brief introduction to Android Basics and Java
Statement Purpose:
The goal of this lecture is to learn the fundamentals of developing Android Applications, from project creation to installation on a physical device. More specifically you should gain the knowledge of how to use basic development tools to support the application development process, as well as the key components of an Android application itself
Activity Outcomes:
After completing this chapter student will be able to understand the following topics.
- Android Development Environment
- Creating an App in Android Studio
- Anatomy of Android Project
- Running the First App
- Ingredients of an Android App
Instructor Note:
These labs assume that you know the Java Programming Language. If you are not yet a Java programmer, consider taking Java Complete Reference J2SE/J2EE. It will get you ready for completing these labs.
Introduction
Android is a mobile operating system that is based on a modified version of Linux. Android, as a system, is a Java-based operating system that runs on the Linux kernel. The system is very lightweight and full featured. It was originally developed by a startup of the same name, Android, Inc. In 2005, as part of its strategy to enter the mobile space, Google purchased Android and took over its development work. Google wanted Android to be open and free; hence, most of the Android code was released under the open source Apache License, which means that anyone who wants to use Android can do so by downloading the full Android source code.
The main advantage of adopting Android is that it offers a unified approach to application development. Developers need only develop for Android, and their applications should be able to run on numerous different devices, as long as the devices are powered using Android.
Android Versions
Android has gone through quite a number of updates since its first release. The follow table shows the various versions of Android and their codenames.
Features of Android
As Android is open source and can be customized by the manufacturers, there are no fixed hardware or software configurations. Android itself supports the following features:
Storage — Uses SQLite, a lightweight relational database, for data storage.
Connectivity — Supports GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth,Wi- Fi, LTE, and WiMAX. Messaging — Supports both SMS and MMS.
Web browser — Based on the open source WebKit, together with Chrome„s V8JavaScript engine.
Media support — Includes support for the following media: H.263, H.264 (in 3GP orMP4 container), MPEG-4 SP, AMR, AMR-WB (in 3GP container), AAC, HE- AAC (in MP4 or 3GP container), MP3, MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP
Hardware support — Accelerometer Sensor, Camera, Digital Compass, Proximity Sensor, and GPS
Multi-touch — Supports multi-touch screens
Multi-tasking — Supports multi-tasking applications
Flash support — Android 2.3 supports Flash 10.1.
Tethering — Supports sharing of Internet connections as a wired/wireless hotspot
Android Architecture Linux Kernel
Since the android architecture is built on top of Linux Kernel, the Kernel is used as a hardware abstraction layer. i.e, It can be used as an abstraction layer between hardware and software. For example, consider the battery function. The devices which run on android will have hardware component like camera, blue tooth, battery etc. The power management interface from the Kernel will interact with the battery (hardware). There is a list of low level interfaces provided by the Kernel such as camera driver, audio drivers, memory management, display driver etc. Libraries The libraries are the APIs which contains the features of android operating system. Android Runtime Contains two elements:
Dalvik Virtual Machine Core Libraries
Dalvik Virtual Machine
The Dalvik Virtual Machine (DVM) is available under Android runtime. The Dalvik virtual machine executes .dex files. The .dex files are provided by DX tool which works as a compiler for android SDK. This DX tool is explained in android SDK tools. The Dalvik virtual machine (DVM) does the job of Java virtual machine (JVM). The role of Dalvik virtual machine is similar to java virtual machine. While java virtual machine executes byte code, on the other side, in android programming Dalvik virtual machine executes Dalvik byte code (.dex files).
Application Framework
The application framework contains libraries for various areas like power management, multimedia, storage access and graphical user interface. The libraries in the framework are written in Java and run on top of the core libraries of the Android Runtime. The application framework of android provides managers for various purposes such as resources handling, content providers, system wide notification etc. The android applications are using the services of these managers. Application On Android, every application runs in its own process, each of which runs in its own virtual machine (VM).
Applications are the android applications which are executed on a device. The applications are the top layer in the android architecture. This layer will consists of pre-installed and our own applications.
The android application we develop goes into this layer.
Activities:
Object-oriented programming (OOP) is a programming language model organized around objects rather than “actions” and data rather than logic. Historically, a program has been viewed as a logical procedure that takes input data, processes it, and produces output data.
- “Class” means a category of things
- “Object” means a particular item that belongs to a class •Also called an “instance”
Activity 1: Example of ARRAYS is given below.
public class TestArray
{
public static void main(String[] args) {
double[] myList= {1.9, 2.9, 3.4, 3.5};
for (inti= 0; i< myList.length; i++) // Printing all array elements
{
System.out.println(myList[i] + ” “);
}}}
Activity 2: Creating class in OOP
Class Declaration
class Circle {
double radius = 1.0;
double findArea(){
return radius * radius * 3.14159; }}
Creating objects
ClassName objectReference= new ClassName();
Accessing Objects
objectReference.data
myCircle.radius
objectReference.method
myCircle.findArea()
Constructors
Constructors are a special kind of methods that are invoked using the new operator when an object is created.
Constructors play the role of initializing objects.
Constructors must have the same name as the class itself.
Constructors do not have a return type—not even void.
Constructor with no parameters is referred to as a default constructor.
Activity 3: An example of calculations of area of circles of different colors is given below
Define the Circle class
public class Circle { // Save as “Circle.java”
double radius;
String color;
//Constructors (overloaded)
public Circle() { // 1st Constructor
radius = 1.0;
color = “red”;
}
public Circle(double r) { // 2nd Constructor
radius = r;
color = “red”;
}
public Circle(double r, String c) { // 3rd Constructor
radius = r;
color = c;
}
// Public methods
public double getRadius()
{
return radius;
}
public String getColor()
{
return color;
}
public double getArea() {
return radius*radius*Math.PI;
}
}
Output of Test Class
Radius is 2.0 Color is blue Area is 12.566370614359172
Radius is 2.0 Color is red Area is 12.566370614359172
Radius is 1.0 Color is red Area is 3.141592653589793
Keyword “this”
public class Circle {
double radius; // Member variable called “radius”
public Circle(double radius) { // Method’s argument also called “radius”
this.radius= radius;
// “this.radius” refers to this instance’s member variable
// “radius” resolved to the method’s argument.
} }
Java -Inheritance
- Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order
- The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).
Activity 4:
Calculator of two numbers
class Calculation{
int z;
public void addition(intx, inty)
{
z = x+y;
System.out.println(“The sum of the given numbers:”+z);
}
public void Substraction(int x,int y)
{
z = x-y;
System.out.println(“The difference between the given numbers:”+z);
}}
public class My_Calculationextends Calculation{
public void multiplication(int x, int y)
{
z = x*y;
System.out.println(“The product of the given numbers:”+z);
}
public static void main(String args[]){
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Substraction(a, b);
demo.multiplication(a, b);
}
OUTPUT
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200
Java -Interfaces
An interface is a reference type in Java, it is similar to class, it is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.
Writing an interface is similar to writing a class. But a class describes the attributes and behaviours of an object. And an interface contains behaviours that a class implements.
Activity 5: an example of interface in java with two methods declaration
/* File name : Animal.java */
interface Animal {
public void eat();
public void travel();}
Implementing Interfaces
- When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface.
- A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.
Activity 6:
Interface implementation
/* File name : MammalInt.java */
public class MammalInt implements Animal{
public void eat(){
System.out.println(“Mammal eats”);
}
public void travel(){
System.out.println(“Mammal travels”);
}
public intnoOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
Activity 7:
Instance Variables (“Fields” or “Data Members”)
class Ship1 {
public double x, y, speed, direction;
public String name;
}
public class Test1 {
public static void main(String[] args) {
Ship1 s1= new Ship1();
s1.x= 0.0;
s1.y= 0.0;
s1.speed= 1.0;
s1.direction= 0.0; // East
s1.name= “Ship1″;
System.out.println(s1.name + ” is initially at (“+ s1.x + “,” + s1.y + “).”);
s1.x = s1.x + s1.speed
- Math.cos(s1.direction * Math.PI/ 180.0);
- s1.y = s1.y + s1.speed
- Math.sin(s1.direction * Math.PI/ 180.0);
- System.out.println(s1.name + ” has moved to (“+ s1.x + “,” + s1.y + “).”);
}}
Output:
Ship1 is initially at (1,0).
Ship2 has moved to (-1.41421,1.41421).
Activity 8:
Methods Activity
class Ship2 {
public double x=0.0, y=0.0, speed=1.0, direction=0.0;
public String name = “UnnamedShip”;
private double degreesToRadians(double degrees){
return(degrees * Math.PI/ 180.0);
}
public void move(){
double angle = degreesToRadians(direction);
x = x + speed * Math.cos(angle);
y = y + speed * Math.sin(angle);
}
public void printLocation(){
System.out.println(name + ” is at (“+ x + “,” + y + “).”);}}
public class Test2 {
public static void main(String[] args) {
Ship2 s1 = new Ship2();
s1.name = “Ship1”;
Ship2 s2 = new Ship2();
s2.direction = 135.0; // Northwest
s2.speed = 2.0;
s2.name = “Ship2”;
s1.move();
s2.move();
s1.printLocation();
s2.printLocation();
}}
Output:
Ship1 is at (1,0).
Ship2 is at (-1.41421,1.41421).
Activity 9:
Setting Up the Development Environment
Download/Install the SDK
For in-depth instructions, visit Android Installation Documentation. Otherwise perform the following steps.
- Go to http://developer.android.com/sdk/index.html.
- Unpack to a convenient location – Remember the full path to this location, we will refer to it as <android_sdk_dir> for the rest of the lab.
- For example, on Linux your home directory is a convenient location.
- <android_sdk_dir> would then be /home/<username>/android_dir.
- Add the path to the <android_sdk_dir>/tools directory to your system PATH
- Linux (Lab Machines Running Fedora):
- Using your favorite text editor, open the .mycshrc file in your home
- Add the following text to the end of the file:
set path=($path <android_sdk_dir>/tools)
set path=($path <android_sdk_dir>/platform-tools
- Open up a terminal, navigate to your home directory and execute the following command:
source .mycshrc
- Windows:
- Right-click My Computer.
- Click Properties.
- Click Advanced
- Click Environment Variables
- Double Click Path under System Variables.
- Add ;<android_sdk_dir>/tools;<android_sdk_dir>/platform-tools to the end of the Variable Values text
- Mac:
- Using your favorite text editor, open the .bash_profile in your home
- Add the following text to the end of the file:
export PATH=$PATH:<android_sdk_dir>/tools
export PATH=$PATH:<android_sdk_dir>/platform-tools
- Open up a terminal, navigate to your home directory and execute the following command:
source .bash_profile
- Navigate to your <android_sdk_dir>/tools directory and type android . Add the appropriate components. See step 4 in http://developer.android.com/sdk/installing.html.
- Test your installation by running adb from the command line. If you did everything right, you should get a long list of help instructions.
Download/Install the Eclipse Plugin
- It is recommended that you use Eclipse 4 or later
- Lab Machines – Fedora Eclipse based on 3.4.2
The version of Eclipse used by the lab machines is missing a vital component and requires adding an additional Eclipse plugin in order to use the Android plugin:
- Click the menu Help -> Software Updates.
- Click the tab Available Software -> Add Site
- Enter http://download.eclipse.org/releases/ganymede into the
Location field.
- Click OK
- Enter WST Common UI into the search/text box at the top of the window (give it a second, it tries to search as you type and its kind of slow).
- Click the checkbox next to WST Common UI.
- Click the Install
- Click the Next
- Accept the terms, click Finish.
- Restart
- Follow the steps in the next bullet 4 Ganymede.
- 4 Ganymede:
- Click the menu Help -> Software Updates.
- Click Available Software tab -> Add Site
- Enter https://dl-ssl.google.com/android/eclipse/ into the “Location“
- Click OK
- Click the checkbox next to Developer Tools.
- Click the Install
- Click the Next
- Accept the terms, click Finish.
- Restart
- 5 Galileo:
- Click Help -> Install New Software .
- Click .. button.
- Enter a name for the site into the Name
- Enter https://dl-ssl.google.com/android/eclipse/ into the Location
- Click OK
- Click the checkbox next to Developer Tools.
- Click the Next
- Accept the terms, click Finish.
- Restart
-
Point Eclipse to <android_sdk_dir>:
- Click the menu Window -> Preferences.
- Click Android from the Hierarchy view on the left hand
- Enter <android_sdk_dir> into the SDK Location
- Click the Apply
- Click the OK
Download/Install the SDK Platform Components
At the time of writing this lab there are are eight different versions of the Android Platform available, ranging from 1.1 to 2.2. It is best practice to develop for the oldest platform available that still provides the functionality you need. This way you can be assured that your application will be supported by as many devices as possible. However, you will still want to download newer versions of the platforms so that you can test your applications against these as well. Due to the size of each platform component you will only be required to download and develop on one platform for the whole class. We will target the highest platform that the G1 phones support, Android 1.6 (API
- Before we can begin developing we must download and install this platform:
- Select the menu Window -> “Android SDK and AVD Manager“, or click on the black phone shaped icon in the toolbar.
- Select Available Packages on the left hand
- Expand the Google Android site in the “Site, Packages, and Archives“
- Check the following items:
- SDK Plaform Android 6, API 4 Revision 3
- Google APIs by Google , Android API 4, Revision 2
- NOTE: Those of you developing on Lab Machines should follow these instructions: http://sites.google.com/site/androidhowto/how-to-1/set-up-the-sdk-on- lab-machines-linux.
- Click Install Selected.
- Accept the Terms for all packages and click Install Accepted.
We’re now ready to develop our application.
Activity 10:
Create “Hello World” Application
Create a new Android Project
- Open
- Click the menu File -> New -> Project.
- Expand the Android folder and select Android Project.
- Name the project lab1<userID>
- For instance, if you userID is jsmith, you would name your project lab1jsmith .
- You can change the location of where you would like to save the project by un-selecting the “Default Location” check box, and supplying your own location.
- Check “Android 6” from the Build Target List.
- This identifies that the project is being built to be compatible with Android versions
1.6 and later.
- Its generally preferred that you choose the lowest build number possible, so as to be compatible with the largest number of existing systems in place.
- This build target can be changed any time later on through the Project Properties
- Fill in the Properties:
- Application Name = Hello World!
- This is the friendly name of the application, that shows up on the
- Application Name = Hello World!
- Package Name = calpoly.android.lab1<userID>
- This is the namespace for the project, follows standard Java
- Create Activity = HelloWorld
- This optional field will automatically create a “Main Activity” class for the You can think of the Main Activity as the Home Page for your application.
- Min SDK Version = 4
- This specifies the minimum API Level on which your application can run. By default this is set to the API Level of the Build Target Platform. As new API’s are added to newer Versions, their API levels increase as A Program that uses an API Level of four won’t be able to run on a platform that has a lower API Level.
- Click “Finish“.
Activity 11:
Take a Tour of the Application
The application you’ve just created is very similar to other java applications you may have created in Eclipse. Look in the Package Explorer side bar. Notice that the Android Development Toolkit(ADT) has generated a number of folders and files for you:
- src: If you expand this out you’ll see the package hiearchy you previously entered. This is where your source code files will
- java: This is the auto-generated stub Activity Class with the name you entered into the project creation wizard. We’ll add some code to this later.
- Android 1.6: This is the version of the library you had chosen in the project creation wizard. The application will be built using this version of ‘android.jar’
- res: This folder will contain all of the resources (a.k.a. external data files) that your application may need. There are three main types of resources that you will be using and the ADT has created a subdirectory for each.
- drawable: This folder will hold image and animation files that you can use in you
- It already contains a file called icon.png which represents the icon that Android will use for your application once it is installed
- layout: This folder will hold xml layout files that the application can use to construct user interfaces. You will learn more about this later, but using a layout resource file is the preferred way to layout your UI.
- It already contains a file called main.xml which defines the user interface for your ‘HelloWorld.java’ Activity class. Double clicking von this file will open up the Android UI Editor that you can use to help generate the xml layout
- values: This folder will hold files that contain value type resources, such as string and integer constants.
- It already contains a file called strings.xml. Double clicking on this file will open up the Android Resource Editor. Notice that there are two strings in there already, one of which is named ‘app_name’. If you select this value, on the right hand side of the editor you should see the Application Name you entered in the project creation wizard. You can use this editor to add new resources to your
- gen: This folder will contain Java files that get auto-generated by ADT. Notice that it already contains one file called “R.java”.
- java: This is a special static class that is used for referencing the data contained in your resource files. If you open this file you will see a number of static inner classes for each of the resource types, as well as static constant integers within them. Notice
that the names of the member variables are the same as the names of the values in your resource files. Each value in a resource file is associated with an integer ID, and that ID is stored in a member variable of the same name, within a static class named after its data type.
- The ‘app_name’ resource value has an ID and is of value type ‘string’. The ADT automatically adds an integer constant to the R.string class and names it ‘app_name’.
- A debugging hint: Occasionally, an Android project will report errors in Eclipse that do not show up in any source code file. Sometimes you can fix this by deleting R.java. When you rebuild your project, R.java gets generated, and perhaps your mysterious errors will
- A second hint: I encourage you to turn on build automatically in Eclipse (Project menu).
- assets: This folder is for asset files, which are quite similar to resources. The main difference being that anything stored in the ‘assets’ folder has to be accessed in the classic ‘file’ manipulation style. For instance, you would have to use the AssetManager class to open the file, read in a stream of bytes, and process the data. You will not be using assets quite as extensively as you will be using
- xml: Every project has a file with this exact name in the root directory. It contains all the information about the application that Android will need to run it:
- Package name used to identify the
- List of Activities, Services, Broadcast Recievers, and Content Provider classes and all of their necessary information, including
- System Permissions the application must define in order to make use of various system resources, like GPS.
- Application defined permissions that other applications must have in order to interact with this application.
- Application profiling
- Libraries and API levels that the application will use.
- properties: Ths file contains all of the project settings, such as the build target you chose in the project creation wizard. If you open the file, you should see ‘target=4’, which is your build target. You should never edit this file manually. If you wish to edit the project properties, do so by right-clicking the project in the ‘Package Explorer’ panel, and selecting ‘Properties’.
The project creation wizard has written the ‘Hello World’ application for you already. A string resource containing the display text has been placed into the res\values\strings.xml file. The value is named ‘hello’.
The xml UI layout has been added to res\layout\main.xml. While you can use the Android Layout Editor to create your xml layout, you can also code them manually yourself. Lets take a look at this file:
- Right-Click on the
- Select Open With -> Text Editor.
Notice the Top Level node, Linear Layout, which defines the style of layout this file will be using. This ‘Linear Layout’ is perhaps the most basic, and specifies that UI elements will be laid out in a continuous line. It has three properties: orientation, width, and height.
Notice the Second Level node, TextView, which defines a UI element for displaying text. It has three properties: width, height, and the text to display. Notice that the text property is not set to “Hello World!”. Instead it is set to reference the resource value which contains the text we want to display. In this case we are choosing to display the contents of the ‘hello’ value. We do this by using the ‘@’ symbol, followed by the value type of the resource (which is a ‘string’), followed by the name of the value (which is ‘hello’).
Activity 12:
Run “Hello World” on the Emulator
On the Emulator
Before we can run the application, we need to setup an Android Vitual Device(AVD), or emulator, to run it on:
- Select the menu Window -> “Android SDK and AVD Manager“, or click on the black phone shaped icon in the toolbar.
- Select Virtual Devices on the left hand
- Click the .. button.
- Give your AVD a
- Select the target build that we would like to run the application on, “Android 1.6 – API Level 4“.
- Click Create AVD and close out the SDK/AVD
We’re now ready to run our application.
- Select the menu Run -> Run.
- Note: The emulator may take a long time to start
- Note: Another way to run your application is to right-click on the project in the Package Explorer, then select Run As -> Android Application.
- You can interact with the emulator using the mouse just like you would with a device. To get started, press the Menu key to see the home screen.
Congratulations! You’ve just created and an Android Application.
On a Physical Device
Before we can run the application on a physical device we need to modify the project, make a configuration change on the phone, and install some drivers for the phone on our development machine. We begin by making your project declare itself as debuggable. It’s possible to do this through the Android Manifest Editor that the ADT provides, however doing this manually helps you understand the manifest better:
- Project Modifications
- From the Package Explorer, double-click the file xml.
- Select the tab labeled xml along the bottom.
- Add android:debuggable=”true” to the inside of the opening <application>
- Save the file and close
- Phone Modifications
- Turn the phone on.
- Navigate to the Home
- Press MENU (the physical button on the device).
- Select Settings -> Applications -> Development.
- Enable the USB debugging
- Installing the Android USB drivers
- Mac OS X: Don’t need to install drivers, it should just
- Windows: Follow instructions here
- Linux:Follow instructions here
Ensure the device is properly connected. Run the application as you would normally. The “Hello World!” app should start on the phone.
Activity 13:
Simple Activity Classes
There are four major types of component classes in any Android application:
- Activities: Much like a Form for a web page, activities display a user interface for the purpose of performing a single task. An example of an Activity class would be one which displays a Login Screen to the user.
- Services: These differ from Activities in that they have no user interface. Services run in the background to perform some sort of task. An example of a Service class would be one which fetches your email from a web server.
- Broadcast Receivers: The sole purpose of components of this type is to receive and react to broadcast announcements which are either initiated by system code or other applications. If you’ve ever done any work with Java Swing, you can think of these like Event Handlers. For example, a broadcast announcement may be made to signal that a WiFi connection has been A Broadcast Receiver for an email application listening for that broadcast may then trigger a Service to fetch your email.
- Content Providers: Components of this type function to provide data from their application to other applications. Components of this type would allow an email application to use the phone’s existing contact list application for looking up and retrieving an email
In this lab, we will be focusing on what Activities are and how they are used. We will cover the other components in later labs. If you would like more information on these components, visit the Android overview page for Application Components.
In case you haven’t figured it out by now, you have already created one of these component classes. That’s right, the HelloWorld class is an Activity Class. It’s a simple user interface designed to greet the user. In the section that follows, we’ll make our application more personal by adding a new Activity class to ask for the user’s name. We’ll then update the existing HelloWorld greeting Activity to display that name.
Note: If you ever have problems getting things to compile in Eclipse, you might try Project -> Clean. You can also try to delete R.java under res, then Project -> Build Project.
Getting the User’s Name
To get the user’s name, you will be creating an Activity class which will allow the user to enter their name into a text field and press a button when finished to proceed to the HelloWorld greeting Activity. There are three separate steps to accomplish here. You must first layout your user interface in XML. Then you must create the Activity class to parse the input from the user and initiate the HelloWorld Activity. Finally, you will have to reconfigure the application to use your new name retrieval Activity on startup.
-
Create the User Interface
Android allows you to layout your user interfaces using a simple XML specification. We will go into more depth on this topic in the next lab, so for now you will be setting up a basic interface using four different GUI elements. Begin by creating a new Android XML file:
- Select the menu File -> New -> Android XML File.
If Android XML File does not appear in the menu:
- Select
- Expand the Android
- Select Android XML File and click Next.
- Ensure the Project matches the name of your project and that the folder is /res/layout.
- Layout files should always go in this
- Enter “xml” as the file name
- The name of your layout files must only contain lower case letters, the numbers 0-9, underscores ‘_’, or periods ‘.’
o [a-z0-9_.]
- Select the Layout radio button.
- Select LinearLayout from the “Select the root ..” drop down and click Finish.
- By default, the file will be opened to the Layout Editor Select the tab labeled
name_getter.xml to switch to the XML Editor.
- This should be located in the bottom left corner of the Layout
Each GUI element derives from the View base class. The first element was added for you when you created the XML layout file and selected LinearLayout from the dropdown menu. You should be able to see an XML opening and closing tag labeled LinearLayout in the editor. Each XML layout file must have a single root view tag, inside which all other view tags are nested. The LinearLayout tag tells Android to arrange elements contained inside it in a straight line in the order in which they appear. Let’s make a few modifications to the LinearLayout by editing the attributes contained in the opening LinearLayout tag:
- Set the attributes
labeled android:layout_width and android:layout_height to “fill_parent” (Include the quotes).
- This tells Android that the LinearLayout should take up all the available width and height on the
- Add an attribute labeled android:orientation and set it to “vertical” .
- This tells Android that elements nested inside the LinearLayout should be laid out in a column, as opposed to a single row as indicated by “horizontal”.
Lets add the other three UI elements to our XML layout file:
- Switch back to the Layout Editor tab.
- The three elements we will add all reside under the folder icon labeled “Views”
- This can be seen along the left hand side of the previous figure, about halfway down
- Scroll down to the item labeled TextView.
- Click and drag the TextView onto the black
- The Layout Editor will pre-populate the label with its auto-generated id, which may look somewhat strange.
- Repeat the previous step for the EditText and Button
- Remember, order matters for the
- This is what you want your UI to look However it may not resemble this quite yet:
- Switch back to the XML Editor to change the attributes of the elements you just
- Notice that all the UI elements you added are nested within the LinearLayout
- There will always be only one root element. You may, however, nest other Layout elements within each other.
- Editing the TextView element:
- This is the label that prompts the user to enter their name. It displays the value contained in the android:text
- Set this attribute to ask the user what their name
- The android:id attribute provides a variable name for referencing this element from within the code.
- Id’s are specified with the syntax of @+id/MyId01 .
- MyId01 is the handle used to identify the element from within your application code via the Static R
- Editing the EditText element:
- This is the text field where the user will input their name. It will default to contain the value set by the android:text
- Remove this attribute, we don’t need
- The android:hint attribute provides a hint to the user when the field is empty, and disappears when text is
- Set this attribute to instruct the user to enter their
- Either make a mental note of the android:id attribute or provide your own variable name which you will use to reference this element from within the code.
- Editing the Button element:
- This is the button that will allow the user to continue to the next HelloWorld greeting
- It displays the value contained in the android:text
- Set this attribute to something like “ok”, “next”, or “submit”.
- Either make a mental note of the current value for the android:id attribute or provide your own variable name which you will use to reference this element from within the
Create the Activity Class
Using the HelloWorld Class from section 2.1 as an example, create a new class that extends android.app.Activity class and implements android.view.View.OnClickListener interface.
- Implement the OnClickListener interface by creating a method stub with the following signature: public void onClick(View v) .
- We’ll fill in this method later
- Declare a member variable of the type widget.EditText
- This will hold a reference to the text field in which the user will enter their name, the same one that you added to the xml layout file.
- Add a method with the following signature: public void onCreate(Bundle savedInstanceState)
- This method will be called when the Activity starts and is where initialization of local and member data will be
- Inside this method perform the following:
- make a call to onCreate(savedInstanceState)
- This should always be done and is to ensure that any necessary parent class initializations are performed.
- make a call to setContentView(R.layout.name_getter)
- When you created the XML layout file earlier, the Android Eclipse Plugin automatically added a static constant to the static R.layout class in the R.java file under the /gen folder. This constant variable has the same name of the file and it’s value is used to identify the layout
- This call tells Android to create a screen based off of the layout
- Make a call to findViewById(R.id.<EditText id>) and set your EditText member variable equal to the return value.
- <EditText id> should be replaced with the android:id that was specified in the xml layout file for the EditText element.
- You will have to explicitly cast the return value to the type of EditText as this method only returns objects of type Object.
- This static constant value was added in the same way as it was done for the layout.name_getter value and serves the same purpose.
- Make a call to findViewById(R.id.<Button id>) and set a local android.widget.Button reference equal to the return value.
- <Button id> should be replaced with the android:id that was specified in the xml layout file for the Button element.
- Make a call to button.setOnClickListener(this) .
- button should be replaced with the local Button reference you just
- Fill in the onClick method stub:
- Retrieve the user entered text from the text field and keep it in a local String variable
- Create an content.Intent object: new Intent(this, HelloWorld.class) .
- We’ll use the Intent object to start the HelloWorld greeting activity and pass it information
- We’ll discuss Intents in more depth in later labs, essentially we use them to interact with other application components.
- You will use the Intent.putExtra(<key>, <value>) method to pass the user entered name to the HelloWorld greeting Activity. This method functions like a hashmap, where values can be stored by associating them with a string key and later retrieved with the same key. You can retrieve this hashmap later by calling getExtras().
- Make a call to <intent>.putExtra(<key>, <value>) ,
- <intent> should be replaced with the intent object you just created.
- <key> should be replaced with a string you will use to access the user’s name
- <value> should be replaced with the user’s name obtained from the text field. To obtain the text from the EditText object, you must call to <editText object>.getText().toString() .
- Make a call to startActivity(<intent>)
- This command will initiate the switch to the HelloWorld greeting
Reconfigure the HelloWorld Application
The Android Manifest contains information on all of the Application’s components, including which component should be used in different scenarios. We need to tell our application to use the new activity on startup instead of the HelloWorld Activity which it was previously using. Begin by Double-Clicking the AndroidManifest.xml file to open it
- Like the Layout file there is also a Manifest Editor. Switch to the XML Editor by clicking the
AndroidManifest.xml tab along the bottom of the editor
- Find the first opening <activity … > tag and change the attribute labeled android:name equal from “.HelloWorld” to “<New Activity Class>“
- Replace <New Activity Class> with the full name of your new Activity
- Look at the package attribute in the <manifest> tag, this declares the top level package for the application. If your activity resides in a sub-package, then you must also include the sub-package in the name of your Activity
- For example:
- application package name in the manifest
tag: android:package=”my.app.basepackage”
- “Activity1”
- fully qualified classpath: app.basepackage.Activity1
- activity tag: <activity android:package=”Activity1″></activity>
- “Activity2”
- fully qualified
classpath: my.app.basepackage.subpackage.Activity2
- activity tag: <activity android:package=”subpackage
.Activity2″></activity>
- The Intent Filter tag you see nested inside the Activity tag is what tells the application that this Activity is the Main, or startup, Activity.
- Add the following opening and closing Activity tag pair underneath the Activity tag pair you just modified, nested inside the Application tag:
- <activity android:name=”HelloWorld” ></activity>
- This declares to the Android device that the application has an Activity component named HelloWorld. If you don’t add this tag, Android will not let you launch this Activity
At this point, you should be able to try running the application. The application should start up and display the name retrieval activity you just created. You should be able to enter your name in the text field and hit the button, after which the old HelloWorld greeting activity should appear.
Greeting the User
Now that we’ve got the name retrieval activity completed, let’s update the HelloWorld greeting Activity to print out the name the user entered. In the OnCreate method of HelloWorld.java:
- Make a call to getIntent().getExtras() to retrieve the hashmap in which you placed the user entered name.
- This will return an os.Bundle object which acts like a hashmap.
- You should check to ensure that this value is not null.
- Retrieve the user entered name from the Bundle
- Make a call to the bundle’s getString(<key>)
- <key> should be replaced with the key String you used to put the user entered name into the hashmap in the name retrieval Activity’s onClick
- You should check to ensure that this value is not null.
- Get a reference to the TextView object in your main.xml layout file (you may need to add an id field).
- Set the text of the TextView object to say Hello <name>!
- <name> should be replaced with the user entered name that you retrieved from the bundle
- Run your
Activity 14:
Exporting Your Application
In order for your application to be run on a physical device, it must be digitally signed with a certificate. The certificate does not need to be signed by a certificate authority like Verisign. It’s acceptable to use a self-signed certificate. As of now, you’ve only been executing your application on your physical device by launching it through Eclipse. By doing it this way, the Eclipse ADT Plugin has been signing your application with its own “debug” certificate. Signing with the “debug” certificate is not acceptable for release to the general public. In this short section you will learn how to generate a new keystore, compile your application as a “.apk” file, create a certificate, and sign it. For more details on the Application signing you can view the documentation on the Android Developer Site.
For those of you who haven’t taken a Security class or are unfamiliar with the idea of Keys, Certificates and how they work, you can read more information about it on Wikipedia.
The Eclipse ADT plugin provides a simple Export Wizard that automates the entire process for you. Follow the instructions on the Android Developer Site on. Make sure to read the short section following this one on. While it’s not that necessary for this lab, it will be important when you release an application to the public.
Make sure to keep track of your “.apk” file. You will be handing it in at the end of the lab as proof that you completed the Lab.
Home Activities:
Activity 1:
Create an android application to print the relevant student name and reg number with table of 2 on TextView. (Printing sequence is like 2×1=2
ali FA13— 2×2=4
ali FA13—)
Create an android application that divides your roll number by 20 and print the table of resultant remainder (only first ten multiples). For example if your roll number is 39, the remainder will be 19 and the output should be
19 x 1 = 19
19 x 2 = 38
19 x 3 = 57
19 x 4 = 76
19 x 5 = 95
19 x 6 = 114
19 x 7 = 133
19 x 8 = 152
19 x 9 = 171
19 x 10 = 190
Assignment:
To complete this lab you will be required to:
Submit your signed “.apk” file to the Digital Dropbox on Blackboard. This effectively provides time-stamped evidence that you submitted the lab on time should there be any discrepancy later on in the course. The name of your application should be lab1<cal-poly-username>.apk. So if your username is ali, then your file would be named lab1ali.apk.
For this student will submit Lab Assignment before the deadline.