Académique Documents
Professionnel Documents
Culture Documents
Of
Computer Science and Engineering
LABORATORY MANUAL
Course Title:
MAD
Class:
Branch:
CSE
Regulation:
R10
No. of Hours/Week:
COURSE OBJECTIVES:
To impart fundamental concepts in the area of mobile computing.
To provide a computer systems perspective on the converging areas of wireless
networking, embedded systems, and software, and to introduce selected topics of current
research interest in the field.
To impart knowledge in wireless and mobile computing and in their applications.
COURSE OUTCOME:
Understanding the systems, protocols and mechanisms to support mobility for mobile
internet user.
Develop networked applications for mobile devices.
Understanding the hardware necessary to support mobility and computation
Understanding the possible applications of mobility to computation
Design and implement a novel mobile computing application
EQUIPMENT/SOFTWARE REQUIRED:
1. JDK and Java Wireless Toolkit must be installed on your system
2. Intel based desktop PC with minimum of 166MHZ
3. No. of Systems required 60 per sess
H.O.D
Sl.No
1
6
7
8
9
10
11
12
13
Page.No
11
14
16
19
22
25
31
33
40
43
46
48
61
14
64
Laboratory
Introduction to J2ME
Installation of Java Wireless Toolkit (J2ME)
1) If the Java Development Kit (JDK) is not there or only having the Java Runtime
Environment (JRE) installed, install the latest JDK from
http://java.sun.com/javase/downloads/index.jsp.
.
2) Next, download the Java Wireless Toolkit (formerly called J2ME Wireless Toolkit)
from: http://java.sun.com/products/sjwtoolkit/download.html.
3) Run the installer (for example, for Windows it is: sun_java_wireless_toolkit- 2_5_2windows.exe). The installer checks whether a compatible Java environment has been preinstalled. If not, it is necessary to uninstall old versions of Java and perform Step 1 again.
J2ME applications using Wireless Tool Kit
To start, launch the java wireless toolkit from your desktop, then it window will appear
like this:
Click on the new project button beside the menu like below
Laboratory
A windows will appear, type the project name and the Midlet className, like in the window
below, we choose
project name: HelloworldProject
Midlet class name: Helloworldmidlet
Then another window called API selected will be show , for just make sure that you the
profile that is selected there, offer the most higher version of Midlet as Profile, and the CLDC
as configuration, choose the MSA as target profiles that give us Midlet 2.1 as profile and the
CLDC1.1 as configuration.
Then click on ok to validate and
you would get this message in the
sun java wireless toolkit window:
The message in the windows
above, said that the project have
been successfully created and the
Laboratory
folder bin, lib, res, src have been created in the appropriate folder of the project and the project
is already open at this time.
-Bin folder: Will content the executable file for your application(. Jar, .jad, Manifest) for a
real deployment,
-Lib folder: Will be where we would specify any extern library that we will use in our
mobile application.
-Src folder: Will be where the source file will be store.
-Res folder: Will content files like pictures that we want to include or use in our mobile
application.
Create the source code file :
. Create a new file and start typing the content of your java file in. Because your class will
inherit from a Midlet class, you must prior import the library that content the definition of the
Midlet like this .
import javax.microedition.midlet.*;
Now save the java file that is in your textpad editor in the src directory situated in the project
directory that has been created when you created your helloworldproject from the Wireless tool
kit,
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class HelloworldMidlet extends MIDlet {
private Form form;
private Display display;
public HelloworldMidlet() {
form = new Form("My First J2ME App");
String msg = "Hello World";
form.append(msg);
display = Display.getDisplay(this);
display.setCurrent(form);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
notifyDestroyed();
}
protected void pauseApp()
3
Laboratory
{
}
protected void startApp() throws MIDletStateChangeException
{
}
}
Launch the wireless toolkit emulator, then open your project by hitting the open project
button and go through the folders where your project have been saved , then select your project
name and hit openproject button like below:
Laboratory
Go to project click on run. The emulator will open, at this time the application is not yet
being executed, it shows a window with the name of your project like below:
Laboratory
To start the application , you must select the Launch button (bottom right of the emulator) to
run your mobile application Then you would get on your mobile emulator screen. a Hello World
message like below:
STEP 1
To Create New J2ME Project
File -> New -> select j2me --> j2me Midlet suite -> click Next
6
Laboratory
Laboratory
Select J2ME Midlet and click Next. Give a name for the midlet.
It create the HelloworldMidlet class and inherit the some methods.
Now add these following code.
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class HelloworldMidlet extends MIDlet
{
private Form form;
private Display display;
public HelloworldMidlet()
{
form = new Form("My First J2ME App");
String msg = "Hello World";
form.append(msg);
display = Display.getDisplay(this);
display.setCurrent(form);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
8
Laboratory
notifyDestroyed();
}
protected void pauseApp()
{
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException
{
// TODO Auto-generated method stub
}
}
STEP 3
We did finish coding now. But in order to run your app you have to do some configuration.
Right click the project --> Run as --> Run Configuration
Click Browse and select the project.
Laboratory
Exercise 1:
Write a J2ME application that shows how to change font size and color.
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import java.io.*;
import java.lang.*;
import javax.microedition.io.*;
import javax.microedition.rms.*;
public class changeFont extends MIDlet
{
public static final boolean COLOR = false;
public static final boolean DEBUG = false;
public static final int WHITE = 0xFFFFFF;
public static final int BLACK = 0x000000;
public static final int BLUE = 0x0000FF;
public static final int LIGHT_GRAY = 0xAAAAAA;
public static final int DARK_GRAY = 0x555555;
private Display myDisplay = null;
private DecodeCanvas decodeCanvas = null;
private boolean painting = false;
10
Laboratory
public changeFont()
{
myDisplay = Display.getDisplay(this);
decodeCanvas = new DecodeCanvas(this);
}
public void startApp() throws MIDletStateChangeException
{
myDisplay.setCurrent(decodeCanvas);
}
public void pauseApp()
{
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException
{
}
class DecodeCanvas extends Canvas
{
private changeFont parent = null;
private int width = getWidth();
private int height = getHeight();
public DecodeCanvas(changeFont parent)
{
this.parent = parent;
}
public void paint(Graphics g)
{
g.setColor(WHITE);
g.fillRect(0, 0, width, height);
Font f1 = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_LARGE);
11
Laboratory
12
Laboratory
Exercise 2:
Write a J2ME program which creates following kind of menu
o Cut
o Copy
o Past
o Delete
o Select all
o Unselect all
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class MenuEvents extends MIDlet {
public ChoiceGroup ch;
public ChoiceGroup ch1;
public Form form;
public Form form1;
public Display display;
public Command View;
public Command Exit;
public Command Back;
public StringItem options;
13
Laboratory
14
Laboratory
Exercise 3:
Write J2ME program which creates following kind of menu[Event Handling]
o Cut
can be on/off
o Copy
can be on/off
o Past
can be on/off
o Delete
can be on/off
o Select all
Put all four Options on
o Unselect all Put all four Options off
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class MenuEvents2 extends MIDlet implements CommandListener,ItemStateListener {
15
Laboratory
Laboratory
{
}
public void commandAction(Command command,Displayable displayable)
{
if(displayable==form)
{
if(command==View)
{
boolean opt[]=new boolean[ch.size()];
options=new StringItem("","");
String values="";
ch.getSelectedFlags(opt);
options.setText("");
for(int i=0;i<opt.length;i++)
{
if(opt[i])
{
values+=ch.getString(i)+"\n";
}
}
options.setText(values);
form1.append(options);
display.setCurrent(form1);
}
else if(command==Exit)
{
destroyApp(true);
notifyDestroyed();
}
}
else if(displayable==form1)
{
if(command==Back)
{
display.setCurrent(form);
options.setText("");
}
}
}
public void itemStateChanged(Item item)
{
if(item==ch1)
{
int i=0;
17
Laboratory
int size=ch.size();
while(i<size)
{
if(ch1.getSelectedIndex()==0)
ch.setSelectedIndex(i, true);
else
ch.setSelectedIndex(i, false);
i++;
}
}
}
}
Output:
Exercise 4:
Create MIDP application which draws a bar graph to the display data values can be
given at int[]array. You can enter four data integers values to the input text field.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class BarGraphMIDlet extends MIDlet implements CommandListener
{
public Form form;
public Command exitCommand;
public Command OkCommand;
public Command backCommand;
public Displayable d;
public Display display;
public TextField textfield1;
public TextField textfield2;
public TextField textfield3;
18
Laboratory
Laboratory
d.setCommandListener(this);
display.setCurrent(d);
}
else if(command==exitCommand)
notifyDestroyed();
}
else if(displayable==d)
{
if(command==backCommand)
display.setCurrent(form);
}
}
}
class BarCanvas extends Canvas{
int[] data;
public int x;
public int y;
public int y1;
public int h;
public BarCanvas(int[] data)
{
this.data=data;
x=10;
}
public void paint(Graphics g)
{
g.setColor(255,255,255);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(255, 125, 100);
int i=0;
y1=data[0];
h=200;
while(i<data.length)
{
y=data[i];
h=200+y1-y;
g.fillRect(x, y,25 , h);
x+=30;
i++;
}
}
}
Output:
20
Laboratory
Exercise 5:
Create an MIDP application which examine that a phone number which a user has
entered is in the given format(Input Checking)
Area code should be one of the following 040,041,050,0400,044
There should 6-8 numbers in telephone number (+ area code)
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class InputChecking extends MIDlet implements CommandListener
{
public Form form1;
public TextField textfield1;
public Command exitCommand;
public Command okCommand;
public StringItem st;
public Display display;
public InputChecking()
{
21
Laboratory
display=Display.getDisplay(this);
form1=new Form("Insert the Phone number");
exitCommand=new Command("Exit",Command.EXIT,1);
okCommand=new Command("Ok",Command.OK,1);
st=new StringItem("Phone Number is ","");
textfield1=new TextField("Phone;","",30,TextField.ANY);
form1.append(textfield1);
form1.addCommand(okCommand);
form1.addCommand(exitCommand);
form1.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(form1);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command cmd,Displayable displayable)
{
if(cmd==exitCommand)
notifyDestroyed();
else if(cmd==okCommand)
{
String s=textfield1.getString();
s=s.replace(' ', '.');
int len=s.length();
int i=0;
int c=0;
String s1="";
while(i<len)
{
if(s.charAt(i)=='.')
{
if(c==0)
{
22
Laboratory
23
Laboratory
Exercise 6:
Write a sample program to show how to make a socket connection from J2ME phone.
Creating the Datagram Server project
1) Click on Wireless Toolkit 2.5.2 under the group: All ProgramsSun Java
(TM) Wireless Toolkit 2.5.2.
2) Click on 'New Project...' button.
24
Laboratory
3) Enter project name as 'DatagramServer'. Enter MIDlet name as 'DatagramServer'. Note that
the Midlet name is the same as the name of the class in the source code, which extends the
MIDlet class, otherwise the application wont run.
4) Another window pops up where it is required to select a target platform. Select 'MIDP 1.0'
from the drop down list.
5) After clicking OK, the project is created; and the Wireless Toolkit tells that the name of the
folder where source code files are created. The path of the source code folder is displayed in the
debug output window.
Creating and Compiling the DatagramServer source files
The Wireless Toolkit does not come with an IDE by default so Use any IDE or a text editor
like Notepad.
1) Create a new text file called DatagramServer.java in the source folder of the project. The
exact path of this folder is displayed in the Wireless Toolkit window.
2) Paste contents DatagramServer.java from into the source file.
Running your Server application on the Phone simulator
1) After compiling the project successfully, click on the Run button in the Wireless Toolkit
window.
2) A graphical window depicting a phone handset will appear with the name of your application
highlighted on its screen as shown below.
3) To start the application, click on the right soft-key (marked with a dot) below the
Launch command.
4) The phone simulator might ask if it is OK to run the network application. Select Yes by
clicking on the appropriate soft-key. The server is now up and running.
5) Keep the server running during the creation, compilation and running of the Datagram Client
application.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
public class DatagramServer extends MIDlet implements CommandListener
{
25
Laboratory
Laboratory
display.setCurrent(form2);
}
}
else if(displayable==form2)
{
if(cmd==exitCommand)
{
notifyDestroyed();
}
else if(cmd==refreshCommand)
{
st.setText(" ");
}
}
}
}
Laboratory
3) A new window pops up. Enter project name as 'DatagramClient'. Enter MIDlet name as
'DatagramClient'. Note that the Midlet name is the same as the name of the class in the source
code, which extends the MIDlet class.
4) Another window pops up where one has to select a target platform. Select 'MIDP 1.0' from
the drop down list.
5) After clicking OK, the project is created and the Wireless Toolkit tells where to place the
source code files. The path of the source code folder is displayed in the debug output window as
explained before.
Creating and Compiling the DatagramClient source files
1) Create a new text file called DatagramClient.java in the source folder of the
project.
2) Paste contents DatagramClient.java into the source file.
3) Then click on the Build button in the Wireless Toolkit window. If the compilation is OK, it
will say Build Complete in the window's debug output window, otherwise it will show the
errors. Note: In the source code, use the System.out.println() statement to output debug
information to this window.
Running your Client application on the Phone simulator
1) After compiling the project successfully, click on the Run button in the Wireless Toolkit
window.
2) A graphical window depicting a phone handset will appear with the name of the application
highlighted on its screen.
3) To start the application, click on the right soft-key (marked with a dot) below the Launch
command.
4) The phone simulator might ask if it is OK to run the network application. Select Yes by
clicking on the appropriate soft-key. The client is now up and running.
5) When the client executes on the phone simulator, one should see a text box with the caption
'Message'. Enter any message and press the right soft-key (corresponding to Send). If the clientserver application is working properly, the screen of the server phone will display the message
sent by the client and the client screen will now display a message sent by the server in response.
The response message from the server is the original client message in reverse.
28
Laboratory
6) Try various features of the phone simulator including the different look-and feel options.
Source code:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
public class DatagramClient extends MIDlet implements CommandListener
{
public Form form1;
public Display display;
public TextField textfield;
public Command sendCommand;
public DatagramClient()
{
display=Display.getDisplay(this);
form1=new Form("Datagram Client");
sendCommand=new Command("send",Command.OK,1);
textfield=new TextField("Enter Text",null,30,TextField.ANY);
form1.append(textfield);
form1.addCommand(sendCommand);
form1.setCommandListener(this);
}
public void startApp() {
display.setCurrent(form1);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command cmd,Displayable d)
{
if(cmd==sendCommand)
{
try
{
DatagramConnection dgc = (DatagramConnection)
Connector.open("datagram://localhost:9001");
try {
while(true)
{
29
Laboratory
Exercise 7:
Authentication with a Web Server
Login to HTTP Server from a J2ME Program
This J2ME sample program shows how to display a simple LOGIN SCREEN on the J2ME
phone and how to authenticate to a HTTP server.
Source Code:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class login extends MIDlet implements CommandListener
{
public Form form1;
30
Laboratory
Laboratory
{
try
{
String
url="http://192.168.5.19:8080/WebApplication7/index.jsp?t1="+t1.getString().trim()
+"&t2="+t2.getString().trim();
ht=(HttpConnection)Connector.open(url);
ist=ht.openInputStream();
byte[] b=new byte[900];
ist.read(b);
String s=new String(b);
s=s.trim();
if(s.equals("ok")) Dept
display.setCurrent(form2);
else
{
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
}
catch(Exception ex)
{
form1.append(ex.toString());
}}}}
Exercise 8
Create a MIDP application, which show to the user 5-10 quiz questions. All questions have
4 possible options and one right option exactly. Application counts and shows to the user
how many right answers were right and shows them to user
Source Code:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import java.io.*;
public class Quiz extends MIDlet implements CommandListener
{
public Form form1;
public Form form2;
public Form form3;
public Form form4;
public Form form5;
32
Laboratory
Laboratory
form1.addCommand(nextCommand);
form1.setCommandListener(this);
ch2=new ChoiceGroup("",Choice.EXCLUSIVE);
ch2.append("b+a", null);
ch2.append("b*a", null);
ch2.append("b/a", null);
ch2.append("b-a", null);
form2.append(ch2);
form2.addCommand(nextCommand);
form2.addCommand(backCommand);
form2.setCommandListener(this);
ch3=new ChoiceGroup("",Choice.EXCLUSIVE);
ch3.append("20", null);
ch3.append("30", null);
ch3.append("10", null);
ch3.append("25", null);
form3.append(ch3);
form3.addCommand(nextCommand);
form3.addCommand(backCommand);
form3.setCommandListener(this);
ch4=new ChoiceGroup("",Choice.EXCLUSIVE);
ch4.append("Rosiah", null);
ch4.append("Jagan", null);
ch4.append("ChandaBabu", null);
ch4.append("Kiran", null);
form4.append(ch4);
form4.addCommand(nextCommand);
form4.addCommand(backCommand);
form4.setCommandListener(this);
ch5=new ChoiceGroup("",Choice.EXCLUSIVE);
ch5.append("8", null);
ch5.append("4", null);
ch5.append("11", null);
ch5.append("23", null);
form5.append(ch5);
form5.addCommand(backCommand);
form5.addCommand(nextCommand);
34
Laboratory
form5.setCommandListener(this);
form6.addCommand(ExitCommand);
}
public void startApp()
{
display.setCurrent(form1);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command cmd,Displayable displayable)
{
if(displayable==form1)
{
if(cmd==nextCommand)
display.setCurrent(form2);
}
else if(displayable==form2)
{
if(cmd==nextCommand)
display.setCurrent(form3);
else if(cmd==backCommand)
display.setCurrent(form1);
}
else if(displayable==form3)
{
if(cmd==nextCommand)
display.setCurrent(form4);
else if(cmd==backCommand)
display.setCurrent(form2);
}
else if(displayable==form4)
{
if(cmd==nextCommand)
display.setCurrent(form5);
else if(cmd==backCommand)
display.setCurrent(form3);
}
35
Laboratory
else if(displayable==form5)
{
if(cmd==nextCommand)
{
if(ch1.getSelectedIndex()==2)
count++;
if(ch2.getSelectedIndex()==0)
count++;
if(ch3.getSelectedIndex()==3)
count++;
if(ch4.getSelectedIndex()==3)
count++;
if(ch5.getSelectedIndex()==3)
count++;
st.setText(String.valueOf(count));
form6.append(st);
form6.append(textfield);
display.setCurrent(form6);
}
}
}
}
Output:
36
Laboratory
ANDROID
1. Introduction
Android is an Operating System for mobile devices developed by Google, which is built upon
Linux kernel. Android competes with Apple's iOS (for iPhone/iPad), RIM's Blackberry,
Microsoft's Windows Phone (previously called Windows Mobile), Sambian OS, and many other
proprietary mobile OSes.
Android is based on Linux with a set of native core C/C++ libraries. Android applications are
written in Java. However, they run on Android's own Java Virtual Machine, called Dalvik Virtual
Machine (DVM), which is optimized to operate on the mobile devices.
Laboratory
Laboratory
to launch. You can change the orientation (between portrait and landscape) of the the emulator
via "Ctrl-F11"
Exercise 9:
Write an android application program that displays hello world using terminal.
Launch Eclipse
1. From "File" menu New Project.. Android Application Project Next.
2. The "New Android Project" dialog appears:
1. In "Application Name", enter "Hello Android" (this is the Android appliation
name that shows up on the real device).
2. In "Project Name", enter "HelloAndroid" (this is the Eclipse's project name).
3. In "Package Name", enter "com.example.helloandroid".
4. In "Build SDK", select the latest version (e.g., Android 4.1 (API 16)).
5. In "Minimum Required SDK", select "API 8 Android 2.2 (Froyo)" - almost all of
the Android devices meet this minimum requirement Next.
3. The "Configure Launcher Icon" dialog appears, which allows you to set the application's
icon to be displayed on the devices Next.
4. The "Create Activitiy" dialog appears. Check "Create Activity" Box Select
"BlankActivity" Next.
5. The "New Blank Activity" dialog appears.
1. In "Activity Name", enter "HelloActivity".
2. In "Layout Name", enter "activity_hello" (default).
3. In "Title", enter "Hello" (this title will appear as the screen title) Finish.
Eclipse ADT creates a default Hello-world Android app.
Run the application by right-click on the project node "Run As" "Android Application".
Once the emulator started, unlock the device by holding and sweeping the "lock" to the right (or
left). It shall launch your Hello-world app, and displays "Hello, world!" on the screen with a title
"Hello".
If your program is not launched automatically, try launching it from the "app menu" manually,
after the emulator is started. Look for the icon "Hello".
39
Laboratory
Trying launching the app from "HOME" "..." Look for the icon "Hello".
Also try "HOME" "..." "MENU" "Manage Apps" Select "HelloAndroid" Uninstall.
40
Laboratory
Source code:
Expand the "src" node. Expand the "com.example.helloandroid" package node.
Open the "HelloActivity.java", and replace it with the following codes:
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
// Construct a TextView UI component
textView.setText("Hello,world");
// Set the text message for TextView
setContentView(textView);
// this Activity sets its content to the TextView
}
}
41
Laboratory
Exercise 10:
Write an android application program that displays hello world using eclipse
Launch Eclipse
1. From "File" menu New Project.. Android Application Project Next.
2. The "New Android Project" dialog appears:
1. In "Application Name", enter "Hello Android" (this is the Android appliation
name that shows up on the real device).
2. In "Project Name", enter "HelloAndroid" (this is the Eclipse's project name).
3. In "Package Name", enter "com.example.helloandroid".
4. In "Build SDK", select the latest version (e.g., Android 4.1 (API 16)).
5. In "Minimum Required SDK", select "API 8 Android 2.2 (Froyo)" - almost all of
the Android devices meet this minimum requirement Next.
3. The "Configure Launcher Icon" dialog appears, which allows you to set the application's
icon to be displayed on the devices Next.
4. The "Create Activitiy" dialog appears. Check "Create Activity" Box Select
"BlankActivity" Next.
5. The "New Blank Activity" dialog appears.
1. In "Activity Name", enter "HelloActivity".
2. In "Layout Name", enter "activity_hello" (default).
3. In "Title", enter "Hello" (this title will appear as the screen title) Finish.
Eclipse ADT creates a default Hello-world Android app.
Run the application by right-click on the project node "Run As" "Android Application".
Once the emulator started, unlock the device by holding and sweeping the "lock" to the right (or
left). It shall launch your Hello-world app, and displays "Hello, world!" on the screen with a title
"Hello".
If your program is not launched automatically, try launching it from the "app menu" manually,
after the emulator is started. Look for the icon "Hello".
42
Laboratory
Trying launching the app from "HOME" "..." Look for the icon "Hello".
Also try "HOME" "..." "MENU" "Manage Apps" Select "HelloAndroid" Uninstall.
43
Laboratory
Source code:
Expand the "src" node. Expand the "com.example.helloandroid" package node.
Open the "HelloActivity.java", and replace it with the following codes:
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
// Construct a TextView UI component
textView.setText("Hello,world");
// Set the text message for TextView
setContentView(textView);
// this Activity sets its content to the TextView
}
}
44
Laboratory
Exercise 11:
Write an android application program that accepts input from the user and displays the
hello name to the user in response as output using eclipse
package com.javapapers.android.form;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class FrmActivity extends Activity
{
Button mButton;
EditText mEdit;
TextView mText;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frm);
mButton = (Button)findViewById(R.id.button1);
mButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view) {
mEdit = (EditText)findViewById(R.id.editText1);
mText = (TextView)findViewById(R.id.textView1);
mText.setText("Welcome "+mEdit.getText().toString()+"!");
}
}
}
}
45
Laboratory
Output:
Exercise 12:
Write an android
demonstrates
Android supports
46
Laboratory
Laboratory
</LinearLayout>
In the main.xml file, observe that the root element is <LinearLayout> and it has a <TextView>
element contained within it. The <LinearLayout> element controls the order in which the views
contained within it appear.
Each View and ViewGroup has a set of common attributes, some of which are shown in Table 1.
Attribute
layout_width
layout_height
layout_marginTop
layout_marginBottom
layout_marginLeft
layout_marginRight
layout_gravity
layout_weight
Description
Specifies the width of the View or ViewGroup
Specifies the height of the View or ViewGroup
Specifies extra space on the top side of the View or ViewGroup
Specifies extra space on the bottom side of the View or ViewGroup
Specifies extra space on the left side of the View or ViewGroup
Specifies extra space on the right side of the View or ViewGroup
Specifies how child Views are positioned
Specifies how much of the extra space in the layout to be allocated to the
View
layout_x
Specifies the x-coordinate of the View or ViewGroup
layout_y
Specifies the y-coordinate of the View or ViewGroup
Table 1 Common attributes of views and viewgroups
Note that some of these attributes are only applicable when a View is in certain specific
ViewGroup(s). For example, the layout_weight and layout_gravity attributes are only applicable
if a View is either in a LinearLayout or TableLayout.
For example, the <TextView> element above has its width filling up the entire width of its parent
(which is the screen in this case) using the fill_parent constant. Its height is indicated by the
wrap_content constant, which means that its height is the height of its content (in this case, the
text contained within it). If you do not wish to have the <TextView> view occupy the entire row,
you can set its layout_width attribute to wrap_content, like this:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
This will set the width of the view to be equal to the width of the text contained within it. You
can also set the width to an absolute value, like this:
48
Laboratory
<TextView
android:layout_width="105px"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
In this case, the width is set to 105 pixels wide. modify the main.xml file by adding a <Button>
view as shown below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TextView
android:layout_width="105px"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:layout_width="100px"
android:layout_height="wrap_content"
android:text="Button"
/>
</LinearLayout>
Figure 3 shows the views laid out from left to right.
49
Laboratory
50
Laboratory
Laboratory
/>
</LinearLayout>
Figure 5 shows that the button is aligned to the right of its parent (which is the LinearLayout)
using the layout_gravity attribute. At the same time, you use the layout_weight attribute to
specify the ratio in which the Button and EditText views occupy the remaining space on the
screen. The total value for the layout_weight attribute must be equal to 1.
Laboratory
android:layout_y="361px"
/>
</AbsoluteLayout>
Figure 6 shows the two Button views located at their specified positions using the
android_layout_x and android_layout_y attributes.
Populate main.xml with the following elements and observe the UI as shown in Figure 7.
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:background="#000044">
<TableRow>
<TextView
android:text="User Name:"
android:width ="120px"
53
Laboratory
/>
<EditText
android:id="@+id/txtUserName"
android:width="200px" />
</TableRow>
<TableRow>
<TextView
android:text="Password:"
/>
<EditText
android:id="@+id/txtPassword"
android:password="true"
/>
</TableRow>
<TableRow>
<TextView />
<CheckBox android:id="@+id/chkRememberPassword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Remember Password"
/>
</TableRow>
<TableRow>
<Button
android:id="@+id/buttonSignIn"
android:text="Log In" />
</TableRow>
</TableLayout>
54
Laboratory
Note that in the above example, there are two columns and four rows in the TableLayout. The
cell directly under the Password TextView is populated with an empty element. If you don't do
this, the Remember Password checkbox will then appear under the Password TextView, like that
shown in Figure 8.
Figure 8 Note the change in the position of the Remember Password view
RelativeLayout
The RelativeLayout lets you specify how child views are positioned relative to each other.
Consider the following main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/RLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TextView
android:id="@+id/lblComments"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Comments"
android:layout_alignParentTop="true"
55
Laboratory
android:layout_alignParentLeft="true"
/>
<EditText
android:id="@+id/txtComments"
android:layout_width="fill_parent"
android:layout_height="170px"
android:textSize="18sp"
android:layout_alignLeft="@+id/lblComments"
android:layout_below="@+id/lblComments"
android:layout_centerHorizontal="true"
/>
<Button
android:id="@+id/btnSave"
android:layout_width="125px"
android:layout_height="wrap_content"
android:text="Save"
android:layout_below="@+id/txtComments"
android:layout_alignRight="@+id/txtComments"
/>
<Button
android:id="@+id/btnCancel"
android:layout_width="124px"
android:layout_height="wrap_content"
android:text="Cancel"
android:layout_below="@+id/txtComments"
android:layout_alignLeft="@+id/txtComments"
/>
</RelativeLayout>
Notice that each view embedded within the RelativeLayout have attributes that allow them to
align with another view. These attributes are:
layout_alignParentTop
layout_alignParentLeft
layout_alignLeft
layout_alignRight
layout_below
layout_centerHorizontal
The value for each of these attributes is the ID for the view that you are referencing. The above
XML UI creates the screen shown in Figure 9.
56
Laboratory
57
Laboratory
Laboratory
Laboratory
switch (view.getId())
{
case R.id.button1:
RadioButton celsiusButton = (RadioButton) findViewById(R.id.radio0);
RadioButton fahrenheitButton = (RadioButton) findViewById(R.id.radio1);
if (text.getText().length() == 0)
{
Toast.makeText(this, "Please enter a valid number",
Toast.LENGTH_LONG).show();
return;
}
float inputValue = Float.parseFloat(text.getText().toString());
if (celsiusButton.isChecked())
{
text.setText(String
.valueOf(convertFahrenheitToCelsius(inputValue)));
celsiusButton.setChecked(false);
fahrenheitButton.setChecked(true);
} else
{
text.setText(String
.valueOf(convertCelsiusToFahrenheit(inputValue)));
fahrenheitButton.setChecked(false);
celsiusButton.setChecked(true);
}
break;
}
}
// Converts to celsius
private float convertFahrenheitToCelsius(float fahrenheit)
{
return ((fahrenheit - 32) * 5 / 9);
}
// Converts to fahrenheit
private float convertCelsiusToFahrenheit(float celsius)
{
return ((celsius * 9) / 5) + 32;
}
}
Compile and build the project.
Output:
60
Laboratory
61
Laboratory
Exercise 14:
Write an android application that shows how to use intents in mobile application
development
Intents are a powerful concept as they allow the creation of loosely coupled applications. Intents
can be used to communicate between any installed application components on the device.
Create a project IntentBrowser
Put the following code in layout/main.xml:
<?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"
android:layout_gravity="center"
>
<Button android:id="@+id/Button01" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Browser"
android:onClick="openBrowser"></Button>
</LinearLayout>
We will start a new Intent with the method :
62
Laboratory
On Clicking Finish IntentBrowser code structure is generated with the necessary Android
Packages being imported along with IntentBrowser.java. IntentBrowser class will look like
following:
Source Code:
package com.sample.IntentBrowser;
import android.app.Activity;
import android.content.Intent;
63
Laboratory
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
public class IntentBrowser extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void openBrowser(View view)
{
Intent i = new Intent("android.intent.action.VIEW",
Uri.parse("http://www.google.com"));
startActivity(i);
}
}
Output:
64