Anda di halaman 1dari 64

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

LAB MANUAL
SUB:

Mobile Application Development Lab

CODE: RT41053 M

CORSE CONDUCTED BY
ANJI REDDY.VAKA

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING


LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY
DENKADA, JONNADA
VIZIANGARAM-535 005

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

Mobile Application Development Lab Manual


Table of Contents
1

Write a J2ME program to show how to change the font size and colour.
Write a J2ME program which creates the following kind of menu. * cut
*copy
*paste
*delete
*selectall
*unselectall
Create a J2ME menu which has the following options (Event Handling):
cut - can be on/off copy - can be

4
5

9
10

Create a MIOP application, which draws a bar graph to the display. Data values can be given at int
[] array.You can enter four data (integer) values to the input text field.
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)
Write a sample program to show how to make a SOCKET Connection from J2ME phone.
This J2ME sample program shows how to how tomake a SOCKET Connection from a
J2ME Phone. Many a times there is a need to connect backend HTTP server from the
J2ME application. Show how to make a SOCKET connection from the phone to port 80.
Login to I OTP 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. Many J2ME applications for security reasons require the authentication of the
user. 'This free J2ME sample program, shows how a J2ME application can do
authentication to the backend server.

Write an Android application program that displays Hello World using Terminal.
Write an Android application program that displays Hello World using Eclipse.
Write an Android application program that accepts a name from the user and displays the hello
name to the user in response as output using Eclipse.

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

11

Write an Android application program that demonstrates the following:


(i) Linear Layout (ii)Relative
Layout (iii)Table Layout
(iv)
Grid View layout

12

Write an Android application program that converts the temperature in Celsius to


Fahrenheit.

13

Write an Android application program that demonstrates intent in mobile


application development.

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

Introduction to J2ME
J2ME (Java 2 Micro Edition) is an advanced technology in Java, developed with the help of Java
Community Process Program. J2ME is a reduced version of the Java API and Java Virtual Machine
that is designed to operate within the limited resources available in the embedded computers and
microcomputers.
J2ME is targeted to developers of intelligent wireless devices and small computing devices who
need to incorporate cross-platform functionality in their products. A key benefit of using J2ME is
compatibility with all Java-enabled devices. Motorola, Nokia, Panasonic all have Java-enabled
devices. A J2ME application is a balance between local and server-side processing.
The Java Community Process Program used a two approaches to addressing the needs of small
computing devices.
Configurations: It is the Java run-time environment and core classes that operate on each device. A
configuration defines the Java Virtual Machine for a particular small computing device. There are
two configurations.
CLDC for handheld devices: The CLDC (Connected Limited Device Configuration) is designed for
16-bit or 32-bit small computing devices with limited memory. These devices usually have between
160KB and 512KB of available memory. Usually these are powered by battery. They use small
bandwidth network wireless connection. These devices use a stripped-down version of the JVM the
KJava Virtual Machine (KVM). These devices include pagers, personal digital assistants, Cell
phones, dedicated terminals, and handheld consumer device.
CDC for plug-in devices: CDC (Connected Device Configuration) devices use a 32bitarchitecture,have at least 2 MB of memory available, and implement a complete functional JVM.
CDC devices include digital set-top boxes, home appliances, navigation systems, point-of-sale
terminals, and smart phones.
Profiles: It is defined for categories of small computing devices. A profile consists of classes that
enable developers to implement features found on a related group of small computing devices. List
of J2ME
Profiles:
1. Profiles Used with CLDC:
2. Mobile Information Device Profile (MIDP)
3. PDA Profile (PDAP)
Profiles Used with CDC:
Foundation Profile
o Game Profile
o Personal Profile
o Personal Basis Profile
o RMI Profile.

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

J2ME Architecture
There are 5 layers in J2ME Architecture.
Those are:
MIDP (Top Most Layer): Which contains Java APIs for user network connections, persistence
storage and the user interface? It also has access to CLDC libraries and MIDP libraries.
J2ME APIs(Profiles): Which consists of the minimum set of application programming interfaces
for the small computing device.
Configurations: Which handles interactions between the profile and the JVM?
JVM Operating System (Bottom Layer).
1,2 and 3 are software Layers.
3) Midlets.
A MIDlet is a J2ME application which operates on an MIDP. A MIDlet is defined with at
least a single class that is derived from the javax.microedition.midlet.MIDlet abstract
class.
Common programming is grouping related MIDlets into a MIDlet suite, which is contained within
the same package and implemented simultaneously. All MIDlets within a MIDlet suite are
considered a group and must be installed and uninstalled as a group.
MIDlets from the same MIDlet suite run the same class. Benefit of the relationship among
MIDlet suite members is that they share the same data.
A MIDlet is an event-based application. All routines executed in the MIDlet are invoked
in response to an event reported to the MIDlet by the application manager. The initial event
that occurs is when the MIDlet is started and the application manager invokes the startApp()
method.
The startApp() method in a typical MIDlet contains a statement that displays a screen of data and
prompts the user to enter a selection from among one or more options. The nature and number of
options is, MIDlet and screen dependent.
A Command object is used to present a user with a selection of options to choose from when a
screen is displayed. Each screen must have a CommandListener.
A CommandListener monitors user events with a screen and causes the appropriate code to execute
based on the current event.
A MIDlet is a class that extends the MIDlet class and is the interface between application statements
and the run-time environment, which is controlled by the application manager. A MIDlet class must
contain three abstract methods that are called by the application manager to manage the life cycle of
the MIDlet. These abstract methods are.
startApp(): called by the application manager when the MIDlet is started and contains statements
that are executed each time the application begins execution. Public and have no return value nor
parameter list.

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

pauseApp(): called before the application manager temporarily stops the MIDlet. The application
manager restarts the MIDlet by recalling the startApp() method. Public and have no return value nor
parameter list.
destroyApp(): called prior to the termination of the MIDlet by the application manager. Public
method without a return value. It has a boolean parameter that is set to true if the termination of the
MIDlet is unconditional, and false if the MIDlet can throw a MIDletStateChangeException.

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

1. Write a J2ME program to show how to change the font size and colour.
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;
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);
7

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

Font f1 = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_LARGE);


Font f2 = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_MEDIUM);
Font f3 = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL);
int yPos = 0;
if (COLOR)
g.setColor(BLUE);
else
g.setColor(LIGHT_GRAY);
g.fillRect(0, yPos, width, f1.getHeight());
if (COLOR)
g.setColor(WHITE);
else
g.setColor(BLACK);
g.setFont(f1);
g.drawString("BIG FONT", 0, yPos, Graphics.LEFT | Graphics.TOP);
yPos = yPos + f1.getHeight() + 10;
g.setFont(f2);
// g.drawLine(0, f1.getHeight() + yPos - 1, width, f1.getHeight() + yPos - 1);
g.drawString("MEDIUM FONT", 0, yPos, Graphics.LEFT | Graphics.TOP);
g.setColor(BLACK);
//g.drawLine(0, f2.getHeight() + yPos - 1, width, f2.getHeight() + yPos - 1);
yPos = yPos + f1.getHeight() + 10;
g.setFont(f3);
g.drawString("SMALL FONT", 0, yPos, Graphics.LEFT | Graphics.TOP);
yPos = yPos + f1.getHeight() + 10;
g.drawLine(0, f3.getHeight() + yPos - 1, width, f3.getHeight() + yPos - 1);
painting = false;
}
}
}
OutPut:

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

2. Create a program which creates to following kind of menu.


* cut
* Copy
* Paste
* delete
* select all
* unselect all

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class MenuCreation extends MIDlet implements CommandListener {
public ChoiceGroup ch;
public Form form;
public Display display;
public Command command;
public StringItem st;
public MenuCreation() {
display=Display.getDisplay(this);
ch=new ChoiceGroup("Edit",Choice.EXCLUSIVE);
ch.append("cut",null);
ch.append("copy",null);
ch.append("paste",null);
ch.append("delete",null);
ch.append("select all",null);
ch.append("unselect all",null);
ch.setSelectedIndex(1, true);
command=new Command("Select list item",Command.OK,1);
form=new Form("");
10

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

form.append(ch);
form.addCommand(command);
form.setCommandListener(this);
st=new StringItem("",""); }
public void startApp() {
display.setCurrent(form); }
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command command,Displayable displayable)
{ if(command==command)
{
st.setText("");
st.setText("your selected option is "+ch.getString(ch.getSelectedIndex())); form.append(st);
}
}
}
Output:

11

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

12

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

3. Create a program which creates a select menu for Event handling


Create a menu which has the following options:
* cut - can be on/off
* copy - can be on/off
* paste - can be on/off
* delete - can be on/off
* select all - put all 4 options on
* unselect all - put all 4 options off
Program:

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class MenuEvents extends MIDlet implements CommandListener,ItemStateListener {
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;
public Item item;
public MenuEvents()
{
display=Display.getDisplay(this);
form=new Form("");
form1=new Form("Selcted Options are");
13

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

ch=new ChoiceGroup("Preferences",Choice.MULTIPLE);
ch.append("cut",null);
ch.append("copy",null);
ch.append("paste",null);
ch.append("delete",null);
ch.setSelectedIndex(1, true);
form.append(ch);
ch1=new ChoiceGroup("",Choice.EXCLUSIVE);
ch1.append("select all",null);
ch1.append("unselect all",null);
ch1.setSelectedIndex(1, true);
form.append(ch1);
View=new Command("View",Command.OK,1);
Exit =new Command("Exit",Command.EXIT,1);
Back=new Command("Back",Command.BACK,1);
form.addCommand(View);
form.addCommand(Exit);
form1.addCommand(Back);
form.setCommandListener(this);
form1.setCommandListener(this);
form.setItemStateListener(this);
}
public void startApp()
{
display.setCurrent(form);
}
14

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

public void pauseApp() {


}
public void destroyApp(boolean unconditional) {
}
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++)< p=""> </opt.length;i++)<>
{
if(opt[i])
{
values+=ch.getString(i)+"";
}

}
options.setText(values);
form1.append(options);
display.setCurrent(form1);
15

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

}
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;
int size=ch.size();
while(i<size)< p=""> </size)<>
{
if(ch1.getSelectedIndex()==0)
ch.setSelectedIndex(i, true);
else
16

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

ch.setSelectedIndex(i, false);
i++;
}
}
}
}
Output:

17

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

4. Create an MIDP application which draws a bargraph to display. Data values can be given at
int[]array?
Step-1:-Start ->AllPrograms->Sun Java Tool Kit->Wireless Tool Kit

Step-2:-Click New Project Enter project Name as FirstMidlet -> Enter ClassName as HelloMidlet>click
on
Create
Project

18

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

Step 3: click settings button and select midlet- >add give midlet name , class name

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;
public TextField textfield4;
public TextField textfield5;
public BarGraphMIDlet()
{
19

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

display=Display.getDisplay(this);
form=new Form("BarGraph");
textfield1=new TextField("Value1:-","",30,TextField.ANY);
textfield2=new TextField("Value2:-","",30,TextField.ANY);
textfield3=new TextField("Value3:-","",30,TextField.ANY);
textfield4=new TextField("Value4:-","",30,TextField.ANY);
textfield5=new TextField("Value5:-","",30,TextField.ANY);
form.append(textfield1);
form.append(textfield2);
form.append(textfield3);
form.append(textfield4);
form.append(textfield5);
OkCommand=new Command("Ok",Command.OK,1);
exitCommand=new Command("Exit",Command.EXIT,1);
backCommand=new Command("Back",Command.BACK,1);
form.addCommand(OkCommand);
form.addCommand(exitCommand);
form.setCommandListener(this);
}
public void startApp() {
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command command,Displayable displayable)
{
if(displayable==form)
{
if(command==OkCommand)
{
int[] data=new int[5];
data[0]=Integer.parseInt(textfield1.getString());
data[1]=Integer.parseInt(textfield2.getString());
data[2]=Integer.parseInt(textfield3.getString());
data[3]=Integer.parseInt(textfield4.getString());
data[4]=Integer.parseInt(textfield5.getString());
d=new BarCanvas(data);
dCommand(backCommand);
d.sd.adetCommandListener(this);
display.setCurrent(d);
} else if(command==exitCommand)
notifyDestroyed();
}
else if(displayable==d)
{
20

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

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++;
}
}
}
Step 4: click BUILD button
Step 5: if build successfully completed then click RUN button
Output:

21

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

22

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

6. Write a sample program to show how to make a SOCKET Connection from J2ME phone.
This J2ME sample program shows how to how to make a SOCKET Connection from a J2ME
Phone. Many a times there is a need to connect backend HTTP server from the J2ME
application. Show how to make a SOCKET connection from the phone to port 80.
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class socket extends MIDlet {
// StreamConnection allows bidirectional communication
private StreamConnection streamConnection = null;
// use OutputStream to send requests
private OutputStream outputStream = null;
private DataOutputStream dataOutputStream = null;
// use InputStream to receive responses from Web server
private InputStream inputStream = null;
private DataInputStream dataInputStream = null;
// specify the connect string
private String connectString = "socket://www.java-samples.com:80";
// use a StrignBuffer to store the retrieved page contents
private StringBuffer results;
// define GUI components
private Display myDisplay = null;
private Form resultScreen;
private StringItem resultField;
public socket() {
// initializing GUI display
results = new StringBuffer();
myDisplay = Display.getDisplay(this);
resultScreen = new Form("Page Content:");
}
public void startApp() {
try {
// establish a socket connection with remote server
streamConnection =
(StreamConnection) Connector.open(connectString);
// create DataOuputStream on top of the socket connection
outputStream = streamConnection.openOutputStream();
dataOutputStream = new DataOutputStream(outputStream);
// send the HTTP request
dataOutputStream.writeChars("GET /index.htm HTTP/1.0 \n");
dataOutputStream.flush();
// create DataInputStream on top of the socket connection
inputStream = streamConnection.openInputStream();
23

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

dataInputStream = new DataInputStream(inputStream);


// retrieve the contents of the requested page from Web server
int inputChar;
while ( (inputChar = dataInputStream.read()) != -1) {
results.append((char) inputChar);
}
// display the page contents on the phone screen
resultField = new StringItem(null, results.toString());
resultScreen.append(resultField);
myDisplay.setCurrent(resultScreen);
} catch (IOException e) {
System.err.println("Exception caught:" + e);
} finally {
// free up I/O streams and close the socket connection
try {
if (dataInputStream != null)
dataInputStream.close();
} catch (Exception ignored) {}
try {
if (dataOutputStream != null)
dataOutputStream.close();
} catch (Exception ignored) {}
try {
if (outputStream != null)
outputStream.close();
} catch (Exception ignored) {}
try {
if (inputStream != null)
inputStream.close();
} catch (Exception ignored) {}
try {
if (streamConnection != null)
streamConnection.close();
} catch (Exception ignored) {}
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}

24

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

7 . Create an MIDP application which examines a phone number, that a user entered in a
given format.
*Area code should be one of the following :040,041,050,0400,044
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*public
CommandListener {

class

InputChecking

extends

MIDlet

implements

public Form form1;


public TextField textfield1;
public Command exitCommand;
public Command okCommand;
public StringItem st;
public Display display;
public InputChecking()
{
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();
25

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

int i=0;
int c=0;
String s1="";
while(i<len)
{
if(s.charAt(i)=='.')
{
if(c==0)
{
if(s1.equals("040") || s1.equals("041") || s1.equals("050") || s1.equals("0400") || s1.equals("044"))
{
c++;
s1="";
}
}
if(c==1)
{
if(s1.length()-1==3)
{
c++;
s1="";
}}}
s1=s1+s.charAt(i);
i++;
}
if(s1.length()-1==3 || s1.length()-1==4 || s1.length()-1==5)
c++;
if(c==3)
st.setText("OK");
else {
st.setText("wrong\n Phone Number Format is xxx xxx xxxx\nArea code must be 040|050|041|0400|
044");
}
form1.append(st);
}}
}
OutPUT:

26

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

27

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

8.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. Many J2ME applications for security reasons require the
authentication of the user. This free J2ME sample program, shows how a J2ME application can do
authentication to the backend server.
Note: Use Apache Tomcat Server as Web Server and Mysql as Database Server.
Login to HTTP Server from a J2ME Program
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. Many J2ME applications for security reasons require the
authentication of the user. This free J2ME sample program, shows how a J2ME application can do
authentication to the backend server.
Note: Use Apache Tomcat Server as Web Server and Mysql as Database Server.

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;
public Command okCommand;
public Display display;
public HttpConnection ht=null;
public InputStream ist=null;
public StringItem st;
public TextField t1;
28

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

public TextField t2;


public Alert alert;
public Form form2;
public login()
{
display=Display.getDisplay(this);
st=new StringItem(" "," Welcome");
alert =new Alert(" ","Wrong UserName
TextField("UserName"," ",30,TextField.ANY);

or

Password",null,AlertType.INFO);

t1=new

t2=new TextField("Password"," ",30,TextField.PASSWORD);


form1=new Form("Login Here");
form2=new Form("Welcome");
okCommand=new Command("Login",Command.OK,1);
form1.addCommand(okCommand);
form1.setCommandListener(this);

form1.append(t1);
form1.append(t2);
form2.append(st);
}

public void startApp() {


display.setCurrent(form1);
}

public void pauseApp() {


29

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
public void commandAction(Command cmd,Displayable d)
{
if(cmd==okCommand)
{
try
{ of
// String url="http://192.168.5.19:8080/WebApplication7/index.jsp?t1=101&t2=aaa"; String
url="http://192.168.5.19:8080/WebApplication7/index.jsp?t1="+t1.getString().trim()+"&t2="+t2
.getString().trim();

//ht=(HttpConnection)Connector.open("http://192.168.5.19:8080/WebApplication7/index.jsp");
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);
30

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

display.setCurrent(alert);
}

}
catch(Exception ex)
{
form1.append(ex.toString());
}

}
}
}

31

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

ANDROID
Android is Google's oft-discussed mobile, wireless, computer, and communications platform. You
can take advantage of the powerful Eclipse environment to build Android applications using the
Android Eclipse plug-in.
System requirements.
Eclipse Platform:
Eclipse is the platform upon which the plug-in runs. Get the latest version of
Eclipse Classic (V3.3.1 was used in this tutorial).
Android Developer Tools
The Android Developer Tools (the Eclipse plug-in) may be installed by following
the instructions found at Installing the Android SDK.
Source code
AndroidManifest.xml snippet This file is the application deployment descriptor for Android
applications.
IntentReceiver This demonstrates the implementation of an IntentReceiver, which is the class
that processes intents as advertised by the IntentFilter tag in the AndroidManifest.xml file.
SaySomething.java This implements an Android activity, the primary entry point to the sample
application.
Main.xml This contains the visual elements, or resources, for use by Android activities.
R.java This file is automatically generated by Android Developer Tools and "connects" the
visual resources to the Java source code.
AndroidManifest.xml complete This lists a full AndroidManfest.xml file, along with a
description of each of the important elements.
MobileServiceCallContacts.java This contains the code necessary to display contacts as well as
react to user input to subsequently perform a Google Maps address lookup.

Android terminology :
Android application development under the Eclipse environment requires knowledge of the Eclipse
environment and the Android platform. An understanding of the terms below is helpful in Android
application development with the Eclipse plug-in.
Open Handset Alliance
This is the organization led by Google Inc., consisting of numerous public and private
organizations.
Android
The flagship product of the Open Handset Alliance. This is an open source operating environment
targeted for mobile devices.
32

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

Emulator
A software tool representative of another system This is often an environment that runs on a
personal computer (IBM, Mac, Linux) that emulates another environment, such as a mobilecomputing device.
Linux
An open source operating system kernel at the heart of many computing platforms, including
servers, desktop computers, networking appliances, and mobile-computing devices. Android runs on
top of a Linux kernel.
Dalvik Virtual Machine
The Dalvik VM is an operating environment found in the Android stack, which interprets
application code at runtime. The Dalvik VM is similar to a compliant Java VM, but the two are not
compatible.
Android basics and required tools
Android is an open source operating system targeted for mobile platforms. At the time of this
writing, it is a software-only platform with no publicly available hardware devices.
The Android platform is best described as a stack because it is a collection of components,
including:
Linux kernel-based operating system
Java programming environment
Tool chain, including compiler, resource compiler, debugger, and emulator
Dalvik VM for running applications
Now that we've briefly introduced the Android platform architecture, let's look at some important
characteristics of the platform from a market perspective.
Architecture of Android:

33

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

9.Write an android application print Hello World


Using Android Application print Hello World
Android SDK, you have to make sure that you have setup your Android development environment
properly as explained in Android - Environment Setup. I also assume that you have a little bit
working knowledge with Eclipse IDE. So let us proceed to write a simple Android Application
which will print "Hello World!". Create Android Application
The first step is to create a simple Android Application using Eclipse IDE. Follow the option
File -> New -> Project and finally select Android New Application wizard from the wizard
list. Now name your application as HelloWorld using the wizard window as follows:

package com.example.helloworld;
public final class R {
public static final class attr {
}
public static final class dimen {
public static final int padding_large=0x7f040002;
public static final int padding_medium=0x7f040001;
public static final int padding_small=0x7f040000;
}
public static final class drawable {
public static final int ic_action_search=0x7f020000;
public static final int ic_launcher=0x7f020001;
}
public static final class id {
public static final int menu_settings=0x7f080000;
}
public static final class layout {
public static final int activity_main=0x7f030000;
}
public static final class menu {
34

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

public static final int activity_main=0x7f070000;


}
public static final class string {
public static final int app_name=0x7f050000;
public static final int hello_world=0x7f050001;
public static final int menu_settings=0x7f050002;
public static final int title_activity_main=0x7f050003;
}
public static final class style {
public static final int AppTheme=0x7f060000;
}
}

35

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

10. write an android application using eclipse to print Hello World.


Procedure:
1. Open Eclipse
2. Open the Emulator
[if you don't have created an AVD then create one using below few steps otherwise you can skip
tillStep3]
*Go to Window menu and click on AVD Manager, which will open Android Virtual Device
Manager in a new window.
*Click on New button
*A new window will be opened and will ask for Name.
*Type a name there.[Ex: MyDevice]
*Then choose target android version from dropdown Target. [Ex: Android 2.2 -API Level 8]
*Now click on Create AVD
*OK, your AVD is now ready to run which you can see in the AVD list on the AVD Manager
window.
*Now, choose the device you just have created and then click on Start button.
3. Go to File >New
4. Click on Project.
5. Select Android Project from Android directory/folder.
6. Click Next button.
7. Type your project name. [Ex: HelloWorld]
8. Click Next.
9. Select a build target. [Ex: Android 2.2]
10. Click Next.
11. Type a valid Package Name. [Ex: com.demo.mydemo]
12. Make sure that Create Activity checkbox is checked.
13. Click Finish.
14. Now the project can be seen, listed on the Navigator.
15. It contains some pre-generated files and folders.
16. Open the Activity file located under src folder .[Ex: src --> com --> demo --> mydemo -->]
17. Delete the entire contents from it.
18. Now, Paste following codepackage
com.demo.mydemo;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloWorldActivity extends Activity {
TextView tv;
@Override
public void onCreate(Bundle bndl) {
super.onCreate(bndl);
tv=new TextView(this);
setContentView(tv);
tv.setText("This is a simple HelloWorld android application !");
}
}
36

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

Run the project from menu Run > Run


or, right click on the project on Navigator and then click on Run As > Android Application

output:

37

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

11 Write Android application program that demonstrates the following


a)Linear Layout b)Relative Layout c)Table Layout d)Grid View Layout
A Layout that arranges its children in a single column or a single row. The direction of the row can
be set by calling setOrientation (). You can also specify gravity, which specifies the alignment of all
the child elements by calling setGravity () or specify that specific children grow to fill up any
remaining space in the layout by setting the weight member of Linear Layout. Layout programs. The
default orientation is horizontal.
Linear Layout
Linear layout can be created in two ways 1. GUI 2. Manually
1. GUI
Create an AndroidApplicationProject and expand the Project,
Expand the RES you can find the Layout, Expand the Layout and you can find the
activity_main.xml auto generated file at the creation of project
Select the Layout and Right-click choose new other Expand Android choose AndroidXML
Layout File

Select Linear Layout it should have small finish and name it with your letter at starting of interested
name but the name and click
Step:3
Add the components in either vertically setVerticalOrientation or linear layout you can set or
horizontally by setHorizontalOrientation

38

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

Step:4
Select SRC expand the packed and open MainActivity.java
setContentView(R.layout.linear); to your created layout name

and

change

Step :5
Run the application by right-clicking MainActivity.java and select RunasRunCofigaration
browse your project Name and click run

Output

39

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

Manually
we show you how to use LinearLayout to display 3 buttons in vertical and horizontal
order, and also how weight works.
Open
res/layout/main.xml
file,
add
3
buttons
within LinearLayout, with horizontal orientation. In this case, the highest weight is
button3, so it will fill up the remaining space in the layout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="horizontal" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_2" />
<Button
android:id="@+id/button3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@string/button_3"
android:layout_weight="1"/>
</LinearLayout>

40

Lendi Institute of Engineering&Technology

MAD LAB MANUAL

Output

b)Relative Layout:
In android , Relative Layout let you position your component base on the nearby
components position. Its the most flexible layout, that allow you to position your
component to display in anywhere you want.
In relative layout, you can see above, below, left and right to arrange the component
position, for example , display a button1 below button2 or display button3 on right of
the button1.

We show you how to arrange position button, textview and editbox via Relative Layout.
Step1:
Create a new layout file Layouts->new->others->AndroidXMLLayoutFile
Note: You have use small letter for the starting letter of the file.
Step2:
Write the content in xml file as shown below:

arrange
/
via
Relativ
eLayout
.

41

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/btnButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1"/>
<Button
android:id="@+id/btnButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_2"
android:layout_toRightOf="@+id/btnButton1"/>
<Button
android:id="@+id/btnButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_3"
android:layout_below="@+id/btnButton1"/>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btnButton3"
android:layout_marginTop="94dp"
android:text="User :"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/textView1"
android:layout_toRightOf="@+id/btnButton3" />
<Button
android:id="@+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"

android:layout_below="@+id/editText1"
android:text="Submit" />
</RelativeLayout>
Step3:
Update the MainActivity.java in the src folder that you have to change the layout name as
seContentView(R.layout.relative)
Step4:
Run the project by selecting project folder and right click choose option Runas>AndroidApplication.

Output

Table Layout:
In Android, TableLayout let you change components in rows and columns, just like the standard
table layout in HTML, <tr> and <td>.
Step1:
Create a new layout file Layouts->new->others->AndroidXMLLayoutFile
Note: You have use small letter for the starting letter of the file.
Step2:
Write the content in xml file as shown below:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<!-- 2 columns -->
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dip" >
<TextView
android:id="@+id/textView1"
android:text="Column 1"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button1"

android:text="Column 2" />


</TableRow>
<!-- edittext span 2 column -->
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dip" >

<EditText
android:id="@+id/editText1"
android:layout_span="2"
android:text="Column 1 &amp; 2" />
</TableRow>
<!-- just draw a red line --> <View
android:layout_height="2dip"
android:background="#FF0000" />
<!-- 3 columns -->
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dip" >
<TextView
android:id="@+id/textView2"
android:text="Column 1"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button2"
android:text="Column 2" />
<Button
android:id="@+id/button3"
android:text="Column 3" />
</TableRow>
<!-- display this button in 3rd column via layout_column(zero based) --> <TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dip" >

<Button
android:id="@+id/button4"
android:layout_column="2"
android:text="Column 3" />
</TableRow>
<!-- display this button in 2nd column via layout_column(zero based) --> <TableRow
android:id="@+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dip" >
<Button
android:id="@+id/button5"
android:layout_column="1"
android:text="Column
</TableRow>

2"

/>

</TableLayout>
Step3:
Update the MainActivity.java folder in the src that you have to change the layout as
setContentView(R.layout.table).
Step4:
Run the project by selecting project folder and right click choose option
Runas->AndroidApplication

Output

Grid Layout:
In Android, GridView let you arranges components in a two-dimensional scrolling grid
Two common GridView are Available:

1. Normal way, just display text in GridView layout.

2. Create a custom adapter to display image and text in GridView layout.


1. Normal GridView example
Display characters from A to Z in GridView layout. Quite simple

Step1:
Navigate to res- > layout- > Create New Layout and name it as main.xml and the
content as shown below
<?xml version="1.0" encoding="utf-8"?>
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridView1"
android:numColumns="auto_fit"
android:gravity="center"
android:columnWidth="50dp"
android:stretchMode="columnWidth"

android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</GridView>
It will creates layout as shown below

Step2: Navigate to Src->your application package-> and create


java file named as as GridViewActivity.java and add the content
shown below

package com.example.grid;
import
android.app.Activity;
import android.os.Bundle;
import
android.widget.AdapterView;
import
android.widget.ArrayAdapter;
import android.widget.GridView;
import
android.widget.TextView;
import android.widget.Toast; import
android.view.View;
import android.widget.AdapterView.OnItemClickListener;
public class GridViewActivity extends Activity {
GridView gridView;
static final String[] numbers = new String[] { "A", "B",
"C", "D", "E",
"F", "G", "H", "I", "J", "K",
"L", "M", "N", "O", "P",
"Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z"};
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);

setContentView(R.layout.main);
gridView = (GridView) findViewById(R.id.gridView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, numbers);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new OnItemClickListener() { public
void onItemClick(AdapterView<?> parent, View v,
int
position,
long
id)
{
Toast.makeText(getApplicationContext(),
((TextView)
v).getText(),
Toast.LENGTH_SHORT).show();
}
});
}
}
Step 3:

Update
AndroidManifest.xml
file
android:name="com.example.grid.GridViewActivity"

contents

Step 4:
Run
the
project
by
right
click
the
GridViewActivity.java
Runas Reconfigurationand Browse the project and click run

Output

10. Write an android application to convert temperature from Celsius to Fahrenheit.

file

1.) Create a new project by File-> New -> Android Project name it
ConvertTemperatureExample.
2.) Write following into main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/myshape"
android:orientation="vertical" >
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</EditText>
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="@string/celsius" >
</RadioButton>
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/fahrenheit" >
</RadioButton>
</RadioGroup>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/calc"
android:onClick="myClickHandler">
</Button>
</LinearLayout>
3.) Create and write following into res/drawable/myshape.xml:
1
<?xml version="1.0" encoding="UTF-8"?>

<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="2dp"
android:color="#FFFFFFFF" />
<gradient
android:endColor="#DDBBBBBB"
android:startColor="#DD777777"
android:angle="90" />
<corners
android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp" />
</shape>
4.) Create and write following into res/values/strings.xml:
<resources>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string
name="title_activity_convert_temperture_example">ConvertTempertureExample</st
ring>
<string name="app_name">Temparature Converter</string>
<color name="myColor">#3399CC</color>
<string name="myClickHandler">myClickHandler</string>
<string name="celsius">to Celsius</string>
<string name="fahrenheit">to Fahrenheit</string>
<string name="calc">Calculate</string>
</resources>
5.) Run for output.
Steps:
1.) Create a project named ConvertTemperatureExample and set the information as stated in the
image.
Build Target: Android 4.0
Application Name: ConvertTemperatureExample
Package Name: com. example. ConvertTemperatureExample
Activity Name: ConvertTemperatureExample
Min SDK Version: 8
2.) Open ConvertTemperatureExample.java file and write following code there:
package com.example.converttemperatureexample;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class ConvertTempertureExample extends Activity {


private EditText text;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (EditText) findViewById(R.id.editText1);
}
// This method is called at button click because we assigned the name
to the
// "On Click property" of the button
public void myClickHandler(View view) {
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;
}
}
Output:

13)Write an android application program that demonstrates intents in mobile


application development
Intent

In Android user interface is displayed through an activity. In Android app development you
might face situations where you need to switch between one Activity (Screen/View) to another.
In this Example we will be discussing about switching between one Activity to another and
sending data between activities

Before getting into complete Example we are going to look at code snippets for handling
activities. Lets assume that our new Activity class name is SecondScreen.java
Opening new Activity
To open new activity
following startActivity() or startActivityForResult() method will be used.
Intent i = new Intent(getApplicationContext(), SecondScreen.class);
StartActivity(i);

Sending parameters to new Activity


To send parameter to newly created activity putExtra() methos will be used.
i.putExtra("key", "value");
// Example of sending email to next screen as // Key = 'email'
// value = 'myemail@gmail.com' i.putExtra("email",
"myemail@gmail.com");
Receiving parameters on new Activity
To receive parameters on newly created activity getStringExtra()
method will be used.
Intent
i
=
getIntent();
i.getStringExtra("key");
// Example of receiving parameter having key value as 'email' // and storing the value in a
variable named myemail
String myemail = i.getStringExtra("email");
Opening new Activity and expecting result
In some situations you might expect some data back from newly created activity. In that
situations startActivityForResult() method is useful. And once new activity is closed you

should you
use onActivityResult() method to read the returned result.
Intent i = new Intent(getApplicationContext(), SecondScreen.class);
startActivityForResult(i, 100); // 100 is some code to identify the returning result
// Function to read the result from newly created activity @Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data); if(resultCode == 100){
// Storing result in a variable called myvar
// get("website") 'website' is the key value result data
String mywebsite = data.getExtras().get("result"); }
}
Sending result back to old activity when StartActivityForResult () is used
Intent i = new Intent();
// Sending param key as 'website' and value as 'androidhive.info'
i.putExtra("website", "AndroidHive.info");
// Setting resultCode to 100 to identify on old activity setResult(100,in);

Closing Activity
To close activity call finish() method Add entry in AndroidManifest.xml To run our application
you should enter your new activity in AndroidManifest.xml file. Add new activity between
<application> tags
<activity android:name=".NewActivityClassName"></activity>
In
this
Example
we
create
two
xml
layouts(screen1.xml,screen2.xml) and two
Activities (FirstScreenActivity.java,SecondScreenActivity.java). The following diagram will
give you an idea about the file structure you will be need in this Example.

1.Create a new project File -> Android Project. While creating a new project give activity
name as FirstScreenActivity.
2. Now you need to create user interface for the FirstScreenActivity.java
3. Create a new xml file in layout folder or rename the main.xml to screen1.xml
Right Click on Layout -> New -> Android XML file and name it as screen1.xml
4. Now insert the following code in screen1.xml to design a small layout. This layout
contains simple form with a button.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:ignore="TextFields,HardcodedText" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Name:
"
tools:ignore="HardcodedText" />

<EditText
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dip" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Email: " />
<EditText
android:id="@+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dip" />
<Button android:id="@+id/btnNextScreen"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dip"
android:text="Send to Next Screen" />
</LinearLayout>
5. Now open your FirstScreenActivity.java and Type the following code. In the following
code we are creating a new Intent and passing parameters on clicking button.

package com.example.firstscreenactivity;
import android.app.Activity; import
android.content.Intent;
import
android.os.Bundle;
import
android.util.Log;
import
android.view.View;
import
android.widget.Button;
import android.widget.EditText;

public class FirstScreenActivity extends Activity { //


Initializing variables
EditText
inputName;
EditText
inputEmail;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen1);
inputName = (EditText) findViewById(R.id.name);
inputEmail = (EditText) findViewById(R.id.email);
Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);
//Listening to button event btnNextScreen.setOnClickListener(new
View.OnClickListener() {
public void onClick(View arg0) {
//Starting a new Intent
Intent nextScreen = new Intent(getApplicationContext(),
SecondScreenActivity.class);
//Sending data to another Activity
nextScreen
.putExtra("name",
nextScreen
.putExtra("email",
inputEmail.getText().toString());

inputName.getText().toString());

Log.e("n", inputName.getText()+"."+ inputEmail.getText());


startActivity(nextScreen);
}
});
}
}
6. Create a class called SecondScreenActivity.java. Right Click on src/yourpackagefolder ->
New -> Class and name it asSecondScreenActivity.java

7. Now we need interface for our Second Actvity. Create a new xml file and name it as
screen2.xml.
Right Click on Layout -> New -> Android XML file and name it as screen2.xml. Insert the
following code in screen2.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical"
tools:ignore="SelectableText,HardcodedText,SpUsage" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="15dip"
android:gravity="center"
android:text="You
Entered..."
android:textSize="25dip"
tools:ignore="SpUsage" />
<TextView
android:id="@+id/txtName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="15dip"
android:textSize="18dip" />
<TextView
android:id="@+id/txtEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_contet"
android:layout_margin="15dip"
android:textSize="18dip" />
<Button
android:id="@+id/btnClose"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dip"
android:text="Close" />

</LinearLayout>

8. Now open SecondScreenActivity.java and type the following code. Here we are simply
reading the parameters and displaying them on to screen
package com.example.firstscreenactivity;
import android.app.Activity; import
android.content.Intent;
import
android.os.Bundle;
import
android.util.Log;
import
android.view.View;
import
android.widget.Button;
import android.widget.TextView;
public class SecondScreenActivity extends Activity { /**
Called when the activity is first created. */ @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen2);
TextView txtName = (TextView) findViewById(R.id.txtName);
TextView txtEmail = (TextView) findViewById(R.id.txtEmail); Button
btnClose = (Button) findViewById(R.id.btnClose);
Intent i = getIntent(); //
Receiving the Data
String name = i.getStringExtra("name"); String
email = i.getStringExtra("email"); Log.e("Second
Screen", name + "." + email);
// Displaying Received
txtName.setText(name);
txtEmail.setText(email);

data

// Binding Click event to Button btnClose.setOnClickListener(new


View.OnClickListener() {
public void
//Closing
finish();
}

onClick(View arg0) {
SecondScreen Activity

});
}
}
9. Now everything is ready and before running your project make

sure that you an entry in AndroidManifest.xml of new activity name


file. Open you AndroidManifest.xml filand modify the code as below
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.firstscreenactivity" android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="
8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true
"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.firstscreenactivity.FirstScreenActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SecondScreenActivity"></activity>
</application>
</manifest>
10. Finally run your project by right clicking on your project folder -> Run As -> 1
Android Application. You can see the application is running by switching between screens.
The below image is output screenshots of both xml files.

Output

Anda mungkin juga menyukai