Mad Lab

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 71

IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

J2ME Introduction
J2ME stands for Java 2 Micro Edition. It is Java's specification
for devices which have limited processing power, storage capabilities
and intermittent or fairly low-bandwidth network connections. These
include mobile phones, pagers, wireless devices and set-top boxes
among others. A key benefit of using J2ME is compatibility with all
Java-enabled devices. Motorola, Nokia, Panasonic all have Java-
enabled devices. The Java Community Process Program used two
approaches for addressing the needs of small computing devices.

J2ME Configuration
J2ME Profiles

J2ME Configuration:

It is the Java run-time environment & core classes that operate


on each device. A configuration defines the Java Virtual Machine for a
particular small computing device. There are two configurations.
These two configurations differ only in their respective memory and
display capabilities.

1. Connected, Limited Device Configuration (CLDC) for handheld


devices:
It includes Pagers, PDA, Cell Phones, and Handheld consumer
devices.
16 or 32 bit small computing devices with limited memory
160 512 KB of memory available for Java
Typically has limited power or battery operated
Uses stripped down version of JVM like KJava Virtual
Machine(KVM)
Network connectivity, often wireless, intermittent, low-
bandwidth (9600bps or less)

2. Connected Device Configuration (CDC) for plug in devices:


It describes the Java environment for digital television set-top
boxes, high end wireless devices and automotive telemetric
systems.
evice is powered by a 32-bit processor
2MB or more of total memory available for Java
network connectivity, often wireless, intermittent, low-
bandwidth (9600bps or less)

1
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

J2ME Profile:

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:

Profiles Used with CLDC:


o Mobile Information Device Profile(MIDP)
o PDA Profile(PDAP)

Profiles Used with CDC:


Foundation Profile
Game Profile
Personal Profile
Personal Basis Profile
RMI Profile.

J2ME Architecture:

There are 5 layers in J2ME Architecture out of them first three


layers software layers. Layers of J2ME architecture are as follows:

MIDP (Top Most Layer): Which contains Java


APIs for user network connections, persistence
storage & 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: This handles interactions


between the profile and the JVM.

JVM
Operating System (Bottom Layer).

2
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Midlet

A MIDlet is J2ME applications which operate on an MIDP. A MIDlet is


defined with at least a single class that is derived from the
javax.microedition.midlet.MIDlet abstract class.

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. Responsibilities of Application Manager for running on the device
by the Device manufacturer are follows:

Installing, executing, and removing a MIDLet Suite.

Giving access to classes of the JVM and CLDC for Each member of the
MIDlet suite.

Makes the Java archive (JAR) file and the Java application descriptor
(JAD) file available to members of the MIDlet suite.

JAR Files:

JAR stands for Java Archive file. It is nothing but collection of all java
classes which are related to particular application. This Jar file includes a
special file known as Manifest file which contains information of class files
included in the Jar file. Nine attributes are defined in this file. The first six
attributes are necessary. The files extension is changed to .mf when the
MIDlet is prepared for deployment. All entries are Name: Value pairs. Each
pair must be terminated with a carriage return. Whitespace between the colon
and the attribute value is ignored. Some of Necessary Attributes of a Manifest
File are:

MIDlet-Name: MIDlet suite name.


MIDlet-Version: MIDlet version number.
MIDlet-Vendor: Name of the vendor who supplied the MIDlet.
MIDlet-n: Attribute per MIDlet.
MicroEdition-Profile: Identifies the J2ME profile that is necessary to
run the MIDlet.
MicroEdition-Configuration: Identifies J2ME configuration necessary to
run MIDlet.
Optional Attributes are
MIDlet-Icon: Icon associated with MIDlet, must be in PNG image
format.
MIDlet-Description: Description of MIDlet.
MIDlet-Info-URL: URL containing more information about the
MIDlet.

JAD Files:

JAD Files are used to pass parameters to a MIDlet without modifying


the JAR file. It is also used to provide the application manager with additional
content information about the JAR file to determine whether the MIDlet suite
can beimplemented on the device. Files must have the .jad extension. The
values of the MIDlet-Name, MIDlet-Version, and MIDlet-Vendor attributes in

3
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

the JAD file must match the same attributes in the manifest. All entries are
name:value pairs. Necessary Attributes are

MIDlet-Name: MIDlet suite name.


MIDlet-Version: MIDlet version number.
MIDlet-Vendor: Name of the vendor who supplied the MIDlet.
MIDlet-n: Location of the JAR file.
MIDlet-Jar-URL: Attribute per MIDlet.
Optional attributes available are
MIDlet-Jar-Size: Size of the JAR file in bytes.
MIDlet-Data-Size: Minimum size (in bytes) for persistent data
storage.
MIDlet-Description: Description of MIDlet.
MIDlet-Delete-Confirm: Confirmation required before removing the
MIDlet suite.
MIDlet-Install-Notify: Send installation status to given URL.
Life Cycle of Midlet

A MIDlet is a class that extends MIDlet class & is the interface between
application statements & run-time environment, which is controlled by
application manager. Basic structure of Midlet program is as follows:

public class BasicMIDletShell extends MIDlet


{public void startApp(){ } public void pauseApp(){ }

public void destroyApp( boolean unconditional){ }}

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 application manager when MIDlet is started &


contains statements that are executed each time the application begins
execution. It is Public method & has no return value or parameter list.

pauseApp(): called before the application manager temporarily stops


MIDlet. The application manager restarts the

o MIDlet by recalling the startApp()


method. It is Public method & has
no return value or parameter list.

destroyApp(): called prior to termination of


MIDlet by the application manager. It is
Public method without a return value. It
has a boolean parameter that is set to
true if the termination of the MIDlet is
unconditional & false if the MIDlet can
throw a MIDletStateChangeException.

4
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Procedure for Development of Midlet Applications:

Select Start > All Programs

Select Sun Java wireless tool kit version 2.5.2_01folder in All


Programs

Click on the new project button beside the menu like below

Enter project name and class name

Create a Source code file in java ME language and save in the path
\j2mewtk\2.5.2\apps\HelloworldProject\src

5
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Now we are going to test our First mobile application that


show helloworld. 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:

To compile the project Click on BUILD button.


To run the program click on RUN button. The out put shows as
below.

6
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Experiment 01:
Implementation of J2ME program to show how to change Font
size & Color
Theory:
Canvas Class [javax.microedition.lcdui]:

Canvas class is available in javax.microedition.lcdui package.


Canvas class is a base class for writing applications that need to
handle low-level events and to issue graphics calls for drawing to the
display. Game applications will likely make heavy use of Canvas class.

paint():Renders the Canvas. The application must implement


this method in order to paint any graphics. The Graphics
object's clip region defines the area of the screen that is
considered to be invalid. A correctly-written paint() routine must
paint every pixel within this region.
protected abstract void paint(Graphics g)

repaint(): Requests a repaint for the entire Canvas.


public final void repaint()

Graphics Class [javax.microedition.lcdui]:

This class provides simple 2D geometric rendering capability.


Drawing primitives are provided for text, images, lines, rectangles, and
arcs. Rectangles and arcs may also be filled with a solid color.
Rectangles may also be specified with rounded corners.

Some of the methods in this class are:

drawstring(): Draws the specified String using the current font


and color. The x,y position is the position of the anchor point.
public void drawString(String str, int x, int y, int
anchor)

setColor():Sets the current color to the specified RGB values. All


subsequent rendering operations will use this specified color.

public void setColor(int red, int green, int blue)

setFont():Sets the font for all subsequent text rendering


operations. If font is null, it is equivalent to
setFont(Font.getDefaultFont()).
public void setFont(Font font)

fillRect():Fills the specified rectangle with the current color. If


either width or height is zero or less, nothing is drawn.
public void fillRect(int x, int y, int width, int height)

Source Code:

7
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Midlet for changing Font Size &


Color: package week1;

import
javax.microedition.lcdui.*;
import
javax.microedition.midlet.*;

public class ChangeFontMidlet extends MIDlet implements


CommandListener { Display dis=Display.getDisplay(this);

FontCanvas fc=new FontCanvas();

Command exit=new Command("Exit


App",Command.EXIT,0); public ChangeFontMidlet() {
}

public void startApp()

{ fc.addCommand(exit);
fc.setCommandListener(t
his); dis.setCurrent(fc);

}
public void
pauseApp() { }
protected void destroyApp(boolean unconditional)
notifyDestroyed()
{ ; }

public void commandAction(Command c,


Displayable d) { if(c==exit)

notifyDestroyed();
}
}
class FontCanvas extends Canvas

{ public void paint(Graphics g)


{ g.setColor(0x0000FF);

g.fillRect(0,0,getWidth(),getHeight());

g.setColor(0xFFFFFF);
g.setFont(Font.getFont(Font.FACE_MONOSPACE,Font.STYLE_
PLAIN,

Font.SIZE_LARGE));
g.drawString("Welcome",0,
0,0); g.setColor(0x00FFFF);
8
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

g.setFont(Font.getFont(Font.FACE_SYSTEM,Font.STYLE_ITALIC,

Font.SIZE_SMALL));
g.drawString("to",0,20
,0);
g.setColor(0xFFFF00);
g.setFont(Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_B
OLD,

Font.SIZE_LARGE));
g.drawString("CSE",0,4
0,0);
}

Output:

9
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Experiment 02:

Implementation of J2ME program which creates following kind of


Menu: Cut, Copy, Paste, Delete, Select All, Unselect All

Theory:
List Class [javax.microedition.lcdui]:

The notion of a select operation on a List element is central to


the user's interaction with the List. The behavior of the select
operation within the different types of lists is described in the
following sections. List objects may be created with Choice types of
Choice.EXCLUSIVE, Choice.MULTIPLE, and Choice.IMPLICIT.

append(): Appends an element to the List.


public int append(String stringPart, Image imagePart)

setTitle():Sets the title of the Displayable. If null is given,


removes the title.

public void setTitle(String s)

addCommand(): Adds a command to the Displayable. The


implementation may choose, for example, to add the command
to any of the available soft buttons or place it in a menu. If the
added command is already in the screen, the method has no
effect.
public void removeCommand(Command cmd)

setCommandListener: Sets a listener for Commands to this


Displayable, replacing any previous CommandListener. A null
reference is allowed and has the effect of removing any existing
listener.

public void setCommandListener(CommandListener l)

Alert Class [javax.microedition.lcdui]:

An alert is a screen that shows data to the user and waits for a
certain period of time before proceeding to the next Displayable. An
alert can contain a text string and an image. The intended use of Alert
is to inform the user about errors and other exceptional conditions.

setTimeOut():Set the time for which the Alert is to be shown.


This must either be a positive time value in milliseconds, or the
special value
o FOREVER.
public void setTimeout(int time)

setType():Sets the type of the Alert. The handling and behavior


of specific AlertTypes is described in AlertType.
public void setType(AlertType type)

10
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

setString():Sets the text string used in the Alert.


public void setString(String str)

Source Code:
package week2;

import
javax.microedition.lcdui.*;
import
javax.microedition.midlet.*;
public class Menu1Midlet extends MIDlet implements CommandListener
{
Display dis=Display.getDisplay(this);
List menu=new List("Edit Menu", Choice.IMPLICIT); Command
exit=new Command("Exit App",Command.EXIT,0); public void
showItem(String item)

{ Alert msg=new Alert(item);


msg.setTimeout(Alert.FOREVER);

msg.setType(AlertType.CONFIRMATI
ON); msg.setString("You have
Selected:\n"+item);
dis.setCurrent(msg);

public Menu1Midlet() {
} public void
startApp()

{ menu.append("Cut", null);
menu.append("Copy", null);
menu.append("Paste", null);
menu.append("Delete", null);
menu.append("Select All",
null); menu.append("Unselect
All", null);
menu.addCommand(exit);
menu.setCommandListener(t
his); dis.setCurrent(menu);

}
public void pauseApp() { }
public void destroyApp(boolean unconditional)
{notifyDestroyed(); }

11
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

public void commandAction(Command c,


Displayable d) { if(c==exit)

notifyDestroye
d(); else

showItem(menu.getString(menu.getSelectedIndex()));
}
}

Output:

12
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Experiment 03:

Implementation of J2ME menu which has following options: Cut,


Copy, Paste, Delete can be ON/OFF, Select All will put all four
options ON, Unselect all will put all four options OFF

Theory:
ChoiceGroup Class [javax.microedition.lcdui]:

A ChoiceGroup is a group of selectable elements intended to be


placed within a Form. The group may be created with a mode that
requires a single choice to be made or that allows multiple choices.
For example, it might use "radio buttons" for the single choice mode
and "check boxes" for the multiple choice mode.

append():Appends an element to the ChoiceGroup.


public int append(String stringPart, Image imagePart)

setSelectedIndex():For ChoiceGroup objects of type MULTIPLE,


this simply sets an individual element's selected state. For
ChoiceGroup objects of type EXCLUSIVE and POPUP, this can
be used only to select an element. That is, the selected
parameter must be true. When an element is selected, the
previously selected element is deselected. If selected is false ,
this call is ignored.

public void setSelectedIndex(int elementNum, boolean


selected)

getSelectedIndex():Returns the index number of an element in


the ChoiceGroup that is selected. For ChoiceGroup objects of
type EXCLUSIVE and POPUP there is at most one element
selected, so this method is useful for determining the user's
choice. Returns -1 if there are no elements in the ChoiceGroup.

public int getSelectedIndex()

setSelectedFlags():Attempts to set the selected state of every


element in the ChoiceGroup. The array must be at least as long
as the size of the ChoiceGroup. If the array is longer, the
additional values are ignored.

public void setSelectedFlags(boolean[] selectedArray)

getSelectedFlags():Queries the state of a ChoiceGroup and


returns the state of all elements in the boolean array
selectedArray_return. Note: this is a result parameter. It must
be at least as long as the size of the ChoiceGroup as returned by
size(). If the array is longer, the extra elements are set to false.
public int getSelectedFlags(boolean[]
selectedArray_return)

13
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

getString():Gets the String part of the element referenced by


elementNum.
public String getString(int elementNum)

ItemStateListener Class [javax.microedition.lcdui]:

This interface is used by applications which need to receive


events that indicate changes in the internal state of the interactive
items within a Form screen. itemStateChanged():Called when
internal state of an Item has been changed by the user.

public void itemStateChanged(Item item)

StringItem Class [javax.microedition.lcdui]:

A StringItem is display-only; the user cannot edit the contents.


Both the label and the textual content of a StringItem may be modified
by the application. The visual representation of the label may differ
from that of the textual contents.
setText():Sets text contents of StringItem. If text is null,
StringItem is set to be empty

public void setText(String text)

getText():Gets the text contents of the StringItem, or null if the


StringItem is empty
public String getText()

Source Code:
package week3;

import
javax.microedition.midlet.*;
import
javax.microedition.lcdui.*;
public class Menu2Midlet extends MIDlet implements ItemStateListener
{

Display dis=Display.getDisplay(this);

Command exit=new Command("Exit


App",Command.EXIT,0); ChoiceGroup menu1=new
ChoiceGroup("",Choice.MULTIPLE); ChoiceGroup
menu2=new ChoiceGroup("",Choice.EXCLUSIVE);
StringItem msg=new StringItem("","Select any one of the
items"); Form form=new Form("Edit Menu");

public Menu2Midlet() { }

14
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

public void startApp()

{s menu1.append("Cut", null);
menu1.append("Copy", null);
menu1.append("Paste", null);
menu1.append("Delete", null);
menu2.append("Select All",
null); menu2.append("Unselect
All", null);
menu2.setSelectedIndex(1,
true); form.append(menu1);
form.append(menu2);
form.append(msg);
form.addCommand(exit);
form.setItemStateListener(this)
; dis.setCurrent(form);

}
public void pauseApp() { }
public void destroyApp(boolean unconditional)
{notifyDestroyed(); }

public void itemStateChanged(Item item)

{ boolean[] ch1=new
boolean[menu1.size()]; boolean[]
ch2=new boolean[menu2.size()];
menu1.getSelectedFlags(ch1);
menu2.getSelectedFlags(ch2);

String s="";

for(int
i=0;i<4;i++) {
if(item==menu2)
ch1[i]=ch2[0];
s=s+ "\n"+ menu1.getString(i)+": "+ch1[i];

}
f(item==menu2)

menu1.setSelectedFlags(
ch1); msg.setText("Status of
Items:"+s);

}}

15
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Output:

16
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Experiment 04:

Implementation of MIDP application which draws bar graph to


display Data Values given in an integer array of four values
entered by the user using input text fields.

Theory:
TextField Class [javax.microedition.lcdui]:

A TextField is an editable text component that may be placed


into a Form. It can be given a piece of text that is used as the initial
value.

getString():Gets the contents of the TextField as a string value.


public String getString()

setString():Sets the contents of the TextField as a string value,


replacing the previous contents.
public void setString(String text)

size():Gets the number of characters that are currently stored in


this TextField.
public int size()

Source Code:
package week4;

import
javax.microedition.midlet.*;
import
javax.microedition.lcdui.*;
public class BarGraphMidlet extends MIDlet implements
CommandListener
{
Display dis=Display.getDisplay(this);

Command exit=new Command("Exit App",


Command.EXIT, 0); Command submit=new
Command("Submit",Command.SCREEN,0); Command
back=new Command("Back",Command.BACK,0);

Form dinput=new Form("Data Input");

TextField t1 = new TextField("Enter Value1", null, 256,


TextField.NUMERIC); TextField t2 = new TextField("Enter Value2",
null, 256, TextField.NUMERIC); TextField t3 = new
TextField("Enter Value3", null, 256, TextField.NUMERIC); TextField
t4 = new TextField("Enter Value4", null, 256, TextField.NUMERIC);
final GraphCanvas chart=new GraphCanvas();

17
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

public BarGraphMidlet() {}
public void startApp()
{ dinput.addCommand(exit);
dinput.addCommand(submit);
dinput.append(t1);
dinput.append(t2);

dinput.append(t3);
dinput.append(t4);
dinput.setCommandListener(this);
dis.setCurrent(dinput);
}
public void pauseApp() { }

public void destroyApp(boolean


unconditional) { notifyDestroyed(); }

public void commandAction(Command c,


Displayable s) { if(c==exit)
notifyDestroye
d(); else
if(c==submit)

{
chart.setData("0"+t1.getString(),"0"+t2.getString(),"0"+t3.getString(),"0"+t
4.getStri
ng());
dis.setCurrent(chart);
}
}
}

final class GraphCanvas extends


Canvas { int
lmar=25,tmar=35,bmar=35;

int
w=getWidth(),h=getHeight()
; String title="Bar Chart";

int hspace=(int)(h-tmar-
bmar)/10; int
vspace=(int)(w-lmar)/5;
18
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

int
bwidth=(int)(vspace/4)
; int v[]={0,0,0,0};
public void setTitle(String t) { title=t; }

public void setData(String v1,String v2,String


v3,String v4) { v[0]=Integer.parseInt(v1);

v[1]=Integer.parseInt(v2);
v[2]=Integer.parseInt(v3);
v[3]=Integer.parseInt(v4);
repaint();
}

public void
paint(Graphics g) {
g.setColor(0x0000FF);

g.fillRect(0,0,w,15);
g.setColor(0xFFFFFF);

g.drawString(title,0,
0,0);
for(int i=0;i<=10;i++)

{ g.drawLine(lmar-3,tmar+i*hspace,w-
2,tmar+i*hspace); g.setColor(0xFFFFFF);
g.drawString(""+(i*10),0,tmar+i*hspace-7, 0);
g.setColor(0xAAAAAA);

g.setColor(0xFFFFFF);
g.drawLine(lmar,tmar,lmar,h-
bmar); for(int i=1;i<=4;i++)

{ g.setColor(0xFFFF00); g.drawString("V"+i,lmar+i*vspace-
5,tmar-15, 0); g.drawString(""+v[i-1],lmar+i*vspace-
5,tmar+(v[i-1]*hspace/10), 0); g.setColor(0xFFFFFF);
g.fillRect(lmar+i*vspace-10,tmar,20,(v[i-1]*hspace/10));

}
}
}

19
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Output:

20
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Experiment 05:

Implementation of MIDP application which examine Phone


number which a user has entered is in given format by checking
Area Code (040, 041,050,044) and Length of Phone number
(should be 6-8 digits)

Theory:
TextField Class [javax.microedition.lcdui]:

A TextField is an editable text component that may be placed


into a Form. It can be given a piece of text that is used as the initial
value.

getString():Gets the contents of the TextField as a string value.


public String getString()

setString():Sets the contents of the TextField as a string value,


replacing the previous contents.

public void setString(String text)

size():Gets the number of characters that are currently stored in


this TextField.
public int size()

StringItem Class [javax.microedition.lcdui]:

A StringItem is display-only; the user cannot edit the contents.


Both the label and the textual content of a StringItem may be modified
by the application. The visual representation of the label may differ
from that of the textual contents.

setText():Sets text contents of StringItem. If text is null,


StringItem is set to be empty
public void setText(String text)

getText():Gets the text contents of the StringItem, or null if the


StringItem is empty

public String getText()

Source Code:
package week5;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class CheckPhoneNoMidlet extends MIDlet implements
CommandListener {

21
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Display
dis=Display.getDisplay(this); Form
form=new Form("Phone No. Input");
Command exit=new Command("Exit App",Command.EXIT,0);
Command submit=new Command("Submit",Command.SCREEN,0);
StringItem res=new StringItem("","");
TextField phno = new TextField("Enter Phone
Number:",null,256,TextField.NUMERIC);

public CheckPhoneNoMidlet() {
}
public void startApp()
{
form.append(phno);
form.append(res);
form.addCommand(exit);
form.addCommand(submit);
form.setCommandListener(this);
dis.setCurrent(form);
}
public void pauseApp() { }
public void destroyApp(boolean unconditional)
{notifyDestroyed();}
public void commandAction(Command c, Displayable s)
{ if (c==exit)
notifyDestroyed();
else if(c==submit)
{ String areacode=phno.getString().substring(0,3); String
phnum=phno.getString().substring(3);
if(areacode.length()==3)
{
if(areacode.equals("040")||areacode.equals("041")||areacode.equals("0
50")||areacode.equals("044"))
{ if(phnum.length()>=6&&phnum.length()<=8)
res.setText("Phone Number is valid...\n Area Code:
"+areacode+"\n Phone Number: "+phnum);
else
res.setText("There should be 6-8 numbers in telephone
number");
}else
res.setText("Areas Code should be one of the following: \n
040, 041, 050,044");
}else
res.setText("Areas Code should be one of the following: 040\n
040, 041, 050, 044");
}}}

22
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Output:

23
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Experiment 06:

Implementation of sample program to show how to make SOCKET


connection from J2ME phone

Theory:
Connector Class [javax.microedition.io]:

The creation of Connections is performed dynamically by


looking up a protocol implementation class whose name is formed
from the platform name & the protocol name of the requested
connection.

open():Create and open a Connection.


public static Connection open(String name) throws
IOException

ServerSocketConnection Class [javax.microedition.io]:

A server socket is accessed using a generic connection string


with the host omitted. For example, socket://:79 defines an inbound
server socket on port 79. The host can be discovered using the
getLocalAddress() method.

acceptAndOpen():Returns a StreamConnection object that


represents a server side socket connection. The method blocks
until a connection is made.
public StreamConnection acceptAndOpen() throws
IOException

StreamConnection Class [javax.microedition.io]:

In a typical implementation of this interface, all


StreamConnections have one underlying InputStream and one
OutputStream.

openInputStream():Open and return an input stream for a


connection.
public InputStream openInputStream() throws IOException

openDataInputStream():Open and return a data input stream


for a connection.

public DataInputStream openDataInputStream() throws


IOException

openOutputStream():Open and return an output stream for a


connection.
public OutputStream openOutputStream() throws
IOException

24
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

openDataOutputStream():Open and return a data output


stream for a connection.

public DataOutputStream
openDataOutputStream()
throws
IOException

close(): Close the connection.


public void close() throws IOException

InputStream Class [java.io]:

This abstract class is the superclass of all classes representing an


input stream of bytes.

read():Reads some number of bytes from input stream & stores


them into buffer array. This method blocks until input data is
available, end of file is detected, or an exception is thrown.

public int read(byte[] b) throws IOException

OutputStream Class [java. io]:

This abstract class is the superclass of all classes representing


an output stream of bytes. An output stream accepts output bytes
and sends them to some sink.

write(): Writes b. length bytes from the specified byte array to


this output stream.

public void write(byte[] b) throws IOException

close(): Closes this output stream & releases any system


resources associated with this stream.
public void close() throws IOException

TextBox Class [javax.microedition.lcdui]:


The TextBox class is a Screen that allows the user to enter and edit
text.

setString():Sets the contents of the TextBox as a string value,


replacing the previous contents.
public void setString(String text)

getString():Gets the contents of the TextBox as a string value


public String getString()

25
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Source Code:

Server
Midlet:
package
week6;

import
java.io.InputStream;
import
java.io.OutputStream;
import javax.microedition.io.Connector;

import
javax.microedition.io.ServerSocketConnection
import
javax.microedition.io.StreamConnection;
import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;
public class ServerMidlet extends MIDlet implements CommandListener
{
Display dis=Display.getDisplay(this);

Command exit=new Command("Exit",


Command.EXIT, 0); TextBox tb=new
TextBox("Server", "", 256, 0);

public ServerMidlet() { }
public void startApp()
{ dis.setCurrent(tb);
try

{ StreamConnection
sc=null; InputStream
in=null; OutputStream
out=null; while(true)

{String pname="",cost="";

tb.setString(tb.getString()+"Waiting for
clients...\n"); ServerSocketConnection

ssc=(ServerSocketConnection)Connector.open("socket://:9002");
sc=ssc.acceptAndOpen();

26
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

in=sc.openDataInputStre
am(); int b;
while((b=in.read())!=-1)

pname=pname+(char)b;
in.close();
tb.setString(tb.getString()+"Client> "+pname+"\n");

if(pname.equals("LAPTOP")) cost="32000";
else if(pname.equals("MOUSE")) cost="300";
else if(pname.equals("MONITOR")) cost="2500";
else cost="Unknown Product";

byte
buf[]=cost.getBytes();
out=sc.openOutputStrea
m(); out.write(buf);
out.close();

sc.close();
ssc.close();
}
}
catch(Exception e)
{ tb.setString(e.toString()); }
}

public void pauseApp() { }

public void destroyApp(boolean


unconditional) { notifyDestroyed(); }

public void commandAction(Command c,


Displayable s) { if (c == exit)

notifyDestroyed();
}

27
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

ClientMidle:
package
week6;

import
java.io.InputStream;
import
java.io.OutputStream;

import javax.microedition.io.Connector;
import
javax.microedition.io.SocketConnection;
import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;
public class ClientMidlet extends MIDlet implements CommandListener
{

Display
dis=Display.getDisplay(this);
StringItem res=new
StringItem("","");

Command exit=new Command("Exit App",


Command.EXIT, 0); Command send=new
Command("Send", Command.SCREEN, 0);

TextField pname=new TextField("Enter Product


Name:",null,256,TextField.ANY); Form form=new Form("Client");

public ClientMidlet() { }
public void startApp()
{ form.append(pname);
form.append(res);
form.addCommand(send);
form.setCommandListener(this);
dis.setCurrent(form);
}
public void pauseApp() { }

public void destroyApp(boolean unconditional)

28
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

{ notifyDestroyed(); }

public void commandAction(Command c,


Displayable s) { if (c == exit)

notifyDestroye
d(); else
if(c==send)

{ try

{ SocketConnection
sc=(SocketConnection)Connector.open("socket://localhost:9002");

OutputStream out=sc.openDataOutputStream();

byte[]
buf=pname.getString().toUpperCase().getBytes()
; out.write(buf);
out.close();

int b;
String cost="";

InputStream
in=sc.openInputStream();
while((b=in.read())!=-1)
cost=cost+(char)b;
in.close();
sc.close();

res.setText("Product Name: "+pname.getString()+"\nCost:


"+cost); pname.setString("");

}
catch(Exception e) { res.setText(e.toString()); }
}}
}

29
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Output:

30
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Experiment 07:

Implementation of J2ME sample program that shows how to display


simple Login Screen on J2ME phone & how to authenticate to HTTP
Server with backend Database

Theory:
TextField Class [javax.microedition.lcdui]:

A TextField is an editable text component that may be placed


into a Form. It can be given a piece of text that is used as the initial
value.

getString():Gets the contents of the TextField as a string value.


public String getString()

setString():Sets the contents of the TextField as a string value,


replacing the previous contents.
public void setString(String text)

size():Gets the number of characters that are currently stored in


this TextField.
public int size()

StringItem Class [javax.microedition.lcdui]:

A StringItem is display-only; the user cannot edit the contents.


Both the label and the textual content of a StringItem may be modified
by the application. The visual representation of the label may differ
from that of the textual contents.

setText():Sets text contents of StringItem. If text is null,


StringItem is set to be empty
public void setText(String text)

getText():Gets the text contents of the StringItem, or null if the


StringItem is empty
public String getText()

Connector Class [javax.microedition.io]:

The creation of Connections is performed dynamically by


looking up a protocol implementation class whose name is formed
from the platform name & the protocol name of the requested
connection.

open():Create and open a Connection.

31
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

public static Connection open(String name) throws


IOException

InputConnection Class [javax.microedition.io]:


This interface defines the capabilities that an input stream connection
must have.

openInputStream():Open and return an input stream for a


connection.
public InputStream openInputStream() throws IOException

openDataInputStream():Open and return a data input stream


for a connection.

public DataInputStream openDataInputStream() throws


IOException

InputStream Class [java.io]:

This abstract class is the superclass of all classes representing an


input stream of bytes.

read():Reads some number of bytes from input stream & stores


them into buffer array. This method blocks until input data is
available, end of file is detected, or an exception is thrown.

Source Code:

Server Servlet:
import
javax.servlet.*;
import java.sql.*;
import java.io.*;
public class Login extends GenericServlet

{ public void service(ServletRequest req, ServletResponse res) throws


ServletException, IOException

{ String
uname=req.getParameter("uname");
String
pwd=req.getParameter("pwd");
PrintWriter pw=res.getWriter();

try

{
Class.forName("sun.jdbc.odbc.JdbcOdbcD
river"); Connection

32
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

con=DriverManager.getConnection("jdbc:odbc:mobiledb
","",""); Statement
smt=con.createStatement();
ResultSet
rs=smt.executeQuery("select * from
users where
uname='"+uname+"' and pwd='"+pwd+"'");
if(rs.next())
pw.println("You are authorized...\nWelcome
to
"+uname);
else

pw.println("Invalid
Username/Password?"); }catch(Exception e) {
pw.println(e.toString()); } pw.close();

}
}

Client
Midlet:
package
week7;

import java.io.InputStream;

import javax.microedition.io.Connector;
import
javax.microedition.io.InputConnection;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class ClientMidlet extends MIDlet implements CommandListener


{

Display
dis=Display.getDisplay(this);
Form form=new Form("Login
Page");

Command submit=new
Command("Submit",Command.SCREEN,0); Command
exit=new Command("Exit App",Command.EXIT,0);

TextField uname=new TextField("Enter User


Name:",null,256,TextField.ANY); TextField pwd=new TextField("Enter

33
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Password:",null,256,TextField.PASSWORD);
StringItem res=new StringItem("","Enter User Name & Password");

public ClientMidlet() {
} public void
startApp()

{
form.append(una
me);
form.append(pwd)
;
form.append(res);
form.addCommand(exit);
form.addCommand(submit);
form.setCommandListener(this);
dis.setCurrent(form);
}
public void pauseApp() { }
public void destroyApp(boolean unconditional)
{notifyDestroyed(); }

public void commandAction(Command c,


Displayable s) { if (c == exit)

notifyDestroye
d(); else
if(c==submit)

submitForm();

}
public void submitForm()

{ InputConnection
ic=null; InputStream
in=null;

try
{

String
url="http://localhost:4040/dbserver/Login?uname="+uname.getString()
+"&pwd="+ pwd.getString();
ic=(InputConnection)Connector.open(url);

34
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

in=ic.openInputStrea
m(); String msg="";

int b;
while((b=in.read())!=-
1)

msg=msg+(char)b;
uname.setString("");
pwd.setString("");
res.setText(msg);
ic.close();
}
catch(Exception e)
{ res.setText(e.toString()); }
}}

Output:

35
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Experiment 08:

Implementation of Client-Server application. Assume that Server


is connected to well maintained database of given Domains like
Student Marks Entry/ City Movie Enquiry / Railway PNR Enquiry
/ Cricket Updates / City Weather Updates / EAMCET Results
Enquiry. Mobile Client is to be connected to Server to fetch
required information.

Theory:
TextField Class [javax.microedition.lcdui]:

A TextField is an editable text component that may be placed


into a Form. It can be given a piece of text that is used as the initial
value.

getString():Gets the contents of the TextField as a string value.


public String getString()

setString():Sets the contents of the TextField as a string value,


replacing the previous contents.

public void setString(String text)

size():Gets the number of characters that are currently stored in


this TextField.
public int size()

StringItem Class [javax.microedition.lcdui]:

A StringItem is display-only; the user cannot edit the contents.


Both the label and the textual content of a StringItem may be
modified by the application. The visual representation of the label may
differ from that of the textual contents.

setText():Sets text contents of StringItem. If text is null,


StringItem is set to be empty
public void setText(String text)

getText():Gets the text contents of the StringItem, or null if the


StringItem is empty

public String getText()

Connector Class [javax.microedition.io]:

The creation of Connections is performed dynamically by


looking up a protocol implementation class whose name is formed
from the platform name & the protocol name of the requested
connection.

36
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

open():Create and open a Connection.


public static Connection open(String name) throws
IOException

InputConnection Class [javax.microedition.io]:


This interface defines the capabilities that an input stream connection
must have.

openInputStream():Open and return an input stream for a


connection.
public InputStream openInputStream() throws IOException

openDataInputStream():Open and return a data input stream


for a connection.
public DataInputStream openDataInputStream() throws
IOException

InputStream Class [java.io]:

This abstract class is the superclass of all classes representing an


input stream of bytes.
read():Reads some number of bytes from input stream & stores
them into buffer array. This method blocks until input data is
available, end of file is detected, or an exception is thrown.

public int read(byte[] b) throws IOException

Source Code:

Server Servlet:
import
javax.servlet.*;
import java.sql.*;
import java.io.*;

public class Enquiry extends GenericServlet

{ public void service(ServletRequest req, ServletResponse res) throws


ServletException, IOException

{ String etype=req.getParameter("etype");
String
equery=req.getParameter("equery");
String msg="",cmd="";

PrintWriter
pw=res.getWriter(); try

37
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:mobiledb
","","");
Statement
smt=con.createStatement();
ResultSet rs=null;

if(etype.equals("STUDENT"))
{ rs=smt.executeQuery("select * from student_db
where
htno='"+equery+"'");
if(rs.next())
{int
s1=rs.getInt("sub1"),s2=rs.getInt("sub2"),s3=rs.getInt("
sub3"); int
s4=rs.getInt("sub4"),s5=rs.getInt("sub5"),s6=rs.getInt("sub6");
msg="Student Marks\nH.T.No.:
"+equery; msg=msg+"\nSubject1: "+s1;
msg=msg+"\nSubject2: "+s2;
msg=msg+"\nSubject3: "+s3;
msg=msg+"\nSubject4: "+s4;
msg=msg+"\nSubject5: "+s5;
msg=msg+"\nSubject6: "+s6;
msg=msg+"\nTotal:"+(s1+s2+s3+s4+s5
+s6);
}
}
else if(etype.equals("MOVIES"))
{rs=smt.executeQuery("select * from movie_db
where
mname='"+equery+"'");
if(rs.next())
{ msg="Movie Information\nMovie
Name:
"+equery;

msg=msg+"\nTheatreName:"+rs.getString("tname");
msg=msg+"\nAddress:"+rs.getString("taddress");
msg=msg+"\nTicketsAvailable:"+rs.getString("tickets");
}

}
else if(etype.equals("PNR"))
{rs=smt.executeQuery("select * from train_db where
pnrno='"+equery+"'");
if(rs.next())
{msg="Train Information\nPNR No.: "+equery;
msg=msg+"\nTrainName:
"+rs.getString("tname");

38
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

msg=msg+"\nFrom: "+rs.getString("from");
msg=msg+"\nTo: "+rs.getString("to");
msg=msg+"\nPassingerName:"+rs.getString("pname");
msg=msg+"\nSeatAlloted:
"+rs.getString("seat");
}
}
else if(etype.equals("CRICKET"))
{rs=smt.executeQuery("select * from cricket_db where
mcode='"+equery+"'");
if(rs.next())
{msg="SportsInformation\nSportsCode:"+equery;
msg=msg+"\n"+rs.getString("team1")+"Vs."+rs.getString("team2");
msg=msg+"\nBatingTeam:"+rs.getString("bteam");
msg=msg+"\nScore: "+rs.getString("score");
}
}
else if(etype.equals("WEATHER"))
{rs=smt.executeQuery("select * from weather_db where
city='"+equery+"'");
if(rs.next())
{msg="Weather Information\nCity: "+equery;
msg=msg+"\nHighTemparature:
"+rs.getString("high_temp");
msg=msg+"\nLowTemparature:
"+rs.getString("low_temp");
}
}
else if(etype.equals("EAMCET"))

{rs=smt.executeQuery("select * from eamcet_db where


htno='"+equery+"'");
if(rs.next()){ints1=rs.getInt("sub1"),s2=rs.getInt("sub2"),s3=rs.getInt("sub
3");
msg="EAMCETInformation\nH.T.No.:
"+equery;
msg=msg+"\nSubject1: "+s1; msg=msg+"\nSubject2: "+s2;
msg=msg+"\nSubject3: "+s3;
msg=msg+"\nTotal:"+(s1+s2+s3);
}
}

if(msg.equals(""))msg="Information not found...";


pw.println(msg);
rs.close();
smt.close();
con.close();

39
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

}catch(Exception e) { pw.println(e.toString()); }
pw.close();
}
}

Client
Midlet:
package
week8;

import java.io.InputStream;
import javax.microedition.io.Connector;
import
javax.microedition.io.InputConnection;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class ClientMidlet extends MIDlet implements CommandListener


{
Display dis=Display.getDisplay(this);

Form form=new Form("Enquiry Information


Page"); List menu=new List("Enquiry Menu",
Choice.IMPLICIT);

Command submit=new
Command("Submit",Command.SCREEN,0); Command
home=new Command("Home",Command.SCREEN,0);
Command exit=new Command("Exit
App",Command.EXIT,0); TextField equery=new
TextField("",null,256,TextField.ANY);

StringItem res=new StringItem("","");


String etype="";

public ClientMidlet() {
} public void
startApp()
{ form.append(equery);
form.append(res);
form.addCommand(home);
form.addCommand(submit);
form.setCommandListener(th
is);

menu.append("Student Marks
Enquiry",null); menu.append("Movies

40
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Enquiry",null); menu.append("PNR
Enquiry",null); menu.append("Cricket
Enquiry",null); menu.append("Weather
Enquiry",null); menu.append("EAMCET
Results Enquiry",null);
menu.setCommandListener(this);
dis.setCurrent(menu);
}
public void pauseApp() { }
public void destroyApp(boolean unconditional)
{notifyDestroyed(); }

public void commandAction(Command c,


Displayable s) { if (c == exit)

notifyDestroyed()
; else if(c==submit)

submitForm();
else if(c==home)

dis.setCurrent(men);
else
{ switch(menu.getSelectedIndex())

{ case 0:

equery.setLabel("EnterStudentH.T.N");
etype="STUDENT";

break;
case 1:

equery.setLabel("EnterMovieName")
; etype="MOVIES";

break;
case 2:

equery.setLabel("EnterPNRNo");
etype="PNR";

break;
case 3:

equery.setLabel("EnterCricketMatchCode"
); etype="CRICKET";

break;
case 4:

equery.setLabel("Enter City
Name:"); etype="WEATHER";

41
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

break;
case 5:

equery.setLabel("Enter Student H.T.


No.:"); etype="EAMCET";

break;
}
res.setText("");
dis.setCurrent(form);
}
}
public void submitForm()

{ InputConnection ic=null;
InputStream in=null;
res.setText("Getting
information..."); try

{String
url="http://localhost:4040/dbserver/Enquiry?etype="+etype+"&equery
="+equery.g etString();

res.setText(url);
ic=(InputConnection)Connector.open(url);

in=ic.openInputStrea
m(); String msg="";

int b;
while((b=in.read())!=-
1)

msg=msg+(char)b;
res.setText(msg);
ic.close();
equery.setString("");
}
catch(Exception e)
{ res.setText(e.toString()); }
}
}

42
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Output:

43
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

44
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Android Introduction

Android, as a system, is a Java-based operating system that


runs on the Linux 2.6 kernel. The system is very lightweight and full
featured. Android applications are developed using Java and can be
ported rather easily to the new platform. If we are familiar with Java
programming or are an OOP developer of any sort, we are likely used
to programmatic user interface (UI) development that is, UI placement
which is handled directly within the program code. Android, while
recognizing and allowing for programmatic UI development, also
supports the newer, XML-based UI layout. XML UI layout is a fairly
new concept to the average desktop developer.

One of the more exciting and compelling features of Android is


that, because of its architecture, third-party applications including
those that are home grown are executed with the same system
priority as those that are bundled with the core system. This is a
major departure from most systems, which give embedded system
apps a greater execution priority than the thread priority available to
apps created by third-party developers. Also, each application is
executed within its own thread using a very lightweight virtual
machine.

Android Architecture:

Android Application Life Cycle:

The Android application life cycle is unique in that the system


controls much of the life cycle of the application. All Android
applications, or Activities, are run within their own process. All of the
running processes are watched by Android and, depending on how
the activity is running, Android may choose to end the activity to
reclaim needed resources. Some of the specific methods called during
the life cycle of an android activity are

onCreate
onStart
Process-specific events (Ex: launching activities/ accessing a
database)
onStop

45
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

onDestroy

Following the same logic as other application life cycles, an


Android application is created, the processes are started, events are
fired, processes are stopped, and the application is destroyed. Though
there are a few differences, many application developers should be
comfortable with the steps in the life cycle.
Procedure for Development of Android Applications:

1. Select Start > All Programs


2. Select Eclipse link in All Programs to open Eclipse application
3. Click on File > New > Other option to get New project dialog box
4. In that dialog box select Android Project from Android folder
5. Click on Next button to get New Android Project dialog box
6. In this dialog box enter following details:
Project Name as desired for the application like
HellowWorld
When we enter project name, Automatically Application
Name & Create Activity detailed will be displayed
Select one of the options available under Build Target
option, this will selects the mobile emulator options
Enter Package name as PackageName.subpackage (Ex:
com.hellow)

7. After entering all details click Next button to create Android


application with following folder structure:
o HellowWorld/
src/

com.Hello
o HellowWorldActivity.java
gen/

com.Hello
o R.java
Android 3.0/

android.jar
Assets/

res/

drawable-hdpi
drawable-ldpi

drawable-mdpi
layout
o main.xml
46
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

values
AndroidManifest.out.xml

AndroidManifest.xml
default.properties
proguard.cfg

8. In this directory structure two files are very importent for the
development of application, they are:

HellowWorldActivity.java: this file is java source for


writing events driven code required for the android
applications

main.xml: this file contains information of layout and


components that are displayed on the android application
screen. Components placed in this xml file can be referred
from Activity java file for writing events code for the
particular components.

9. After editing the code, Right click on the desired application from
Package Explorer window , click on Run As > Android
Application option to execute the application

47
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Experiment 09:

Implementation of Android application program that displays


Hello World using Terminal

Source Code:
Main.xml:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/androi
d" android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />

</LinearLayout>
HelloWorldActivity.j
ava: package
com.Hello;

import
android.app.Activity;
import android.os.Bundle;
import
android.widget.TextView;

public class HelloWorldActivity extends Activity


{public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

TextView txtHelloWorld = new


TextView(this); txtHelloWorld.setText("Hello ,
world! How are you");
setContentView(txtHelloWorld);

}}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>

<manifest
xmlns:android="http://schemas.android.com/apk/res/a
ndroid" package="com.Hello"

android:versionCode="1
"

48
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

android:versionName="
1.0">

<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon"
android:label="@string/app_name"> <activity
android:name=".HelloWorldActivity"

android:label="@string/app_n
ame"> <intent-filter>

<action android:name="android.intent.action.MAIN" />

<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>
</application>
</manifest>
Output:

49
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Experiment 10:

Implementation of Android application program that displays


Hello World using Eclipse

Source Code:
Main.xml:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/androi
d" android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />

</LinearLayout>

HelloWorldActivity.j
ava: package
com.Hello;

import
android.app.Activity;
import android.os.Bundle;
import
android.widget.TextView;

public class HelloWorldActivity extends Activity


{public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

TextView txtHelloWorld = new


TextView(this); txtHelloWorld.setText("Hello ,
world! How are you");
setContentView(txtHelloWorld);

}
}

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

50
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

<manifest
xmlns:android="http://schemas.android.com/apk/res/a
ndroid" package="com.Hello"

android:versionCode="1
"
android:versionName="
1.0">

<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon"
android:label="@string/app_name"> <activity
android:name=".HelloWorldActivity"

android:label="@string/app_n
ame"> <intent-filter>

<action android:name="android.intent.action.MAIN" />

<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>
</application>
</manifest>
Output:

51
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Experiment 11:

Implementation of Android application program that accepts


Name from the user & displays the Hello Name to the user in
response as output using Eclipse

Source Code:
Main.xml:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/androi
d" android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<EditText android:id="@+id/editText1"
android:hint="Enter_User_Name"
android:layout_height="wrap_content"
android:layout_width="match_parent"> </EditText>

<Button android:text="Accept"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button
>

<TextView android:text="" android:layout_height="wrap_content"


android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content"
android:id="@+id/textView1"></TextView> </LinearLayout>

HelloUserActivity.jav
a: package
com.HelloUser; import
android.app.Activity;
import
android.os.Bundle;
import
android.view.View;

import
android.view.View.OnClickListener;
import android.widget.Button;

import
android.widget.EditText;
import
android.widget.TextView;

public class HelloUserActivity extends Activity

52
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

{ EditText ed;
Button
Accept;
TextView
show;

public void onCreate(Bundle


savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed=(EditText)findViewById(R.id.editText1);
Accept=(Button)findViewById(R.id.button1);

show=(TextView)findViewById(R.id.textVi
ew1); Accept.setOnClickListener(new
OnClickListener()
{public void onClick(View v)

{ String
Value=ed.getText().toString();
show.setText("Hello "+Value);

}
});
}
}

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

<manifest
xmlns:android="http://schemas.android.com/apk/res/a
ndroid" package="com.HelloUser"

android:versionCode="1
"
android:versionName="
1.0">

<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon"
android:label="@string/app_name"> <activity
android:name=".HelloUserActivity"

android:label="@string/app_n
ame"> <intent-filter>

<action android:name="android.intent.action.MAIN" />

53
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>
</application>
</manifest>

Output:

54
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Experiment 12:

Implementation of Android application program that


demonstrates various layouts like Linear Layout, Relative Layout,
Table Layout and Grid View Layout

12. a) Linear
Layout: Source
Code:
Main.xml:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/androi
d" android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<Button android:text="Button"
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>

<Button android:text="Button"
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>

<Button android:text="Button"
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>

<Button android:text="Button"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
</LinearLayout>

LinearLayoutActivity.j
ava: package
com.LinearLayout;
import
android.app.Activity;
import
android.os.Bundle;

public class LinearLayoutActivity extends Activity

{ public void onCreate(Bundle


savedInstanceState) {
super.onCreate(savedInstanceState);

55
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

setContentView(R.layout.main);
}
}

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

<manifest
xmlns:android="http://schemas.android.com/apk/res/a
ndroid" package="com.LinearLayout"
android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon"
android:label="@string/app_name"> <activity
android:name=".LinearLayoutActivity"

android:label="@string/app_n
ame"> <intent-filter>

<action android:name="android.intent.action.MAIN" />

<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>

56
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

</application>
</manifest>

Output:

57
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

12. b) Relative
Layout: Source Code:
Main.xml:
<?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"
android:id="@+id/relativeLayout1">

<Button android:text="parent button"


android:layout_width="wrap_content"
android:id="@+id/button2" android:layout_height="wrap_
content" android:layout_alignParentRight="true"></Button>

<Button android:text="child button"


android:layout_width="wrap_content"
android:id="@+id/button1"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"></Button>
</RelativeLayout>

RelativeLayoutActivity
.java: package
com.Relative;

import
android.app.Activity;
import
android.os.Bundle;

public class RelativeLayoutActivity extends Activity


{public void onCreate(Bundle savedInstanceState)

{
super.onCreate(savedInstanc
eState);
setContentView(R.layout.mai
n);

}
}

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

58
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

<manifest
xmlns:android="http://schemas.android.com/apk/res/a
ndroid" package="com.Relative" android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon"
android:label="@string/app_name"> <activity
android:name=".RelativeLayoutActivity"

android:label="@string/app_n
ame"> <intent-filter>

<action android:name="android.intent.action.MAIN" />

<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>
</application>
</manifest>
Output:

59
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

12. c) Table
Layout: Source
Code:
Main.xml:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/androi
d" android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<TableLayout android:layout_width="match_parent"
android:id="@+id/tableLayout1"
android:layout_height="wrap_content">

<TableRow android:id="@+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<Button android:text="1"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>

<Button android:text="2"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>

<Button android:text="3"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>

<Button android:text="4"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>

<TableRow android:id="@+id/tableRow6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TableRow>

<TableRow android:id="@+id/tableRow7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TableRow>

</TableRow>

<TableRow android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

60
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

<Button android:text="5"
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>

<Button android:text="6"
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Butto
n>

<Button android:text="7"
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Butto
n>

<Button android:text="8"
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Butto
n>

</TableRow>
</TableLayout>
</LinearLayout>

TableLayoutActivity.j
ava: package
com.Table;
import
android.app.Activity;
import
android.os.Bundle;
public class TableLayoutActivity extends Activity

{ public void onCreate(Bundle


savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.main);
}
}

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

<manifest
xmlns:android="http://schemas.android.com/apk/res/a
ndroid" package="com.Table"
61
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

android:versionCode="1
"
android:versionName="
1.0">

<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon"
android:label="@string/app_name"> <activity
android:name=".TableLayoutActivity"

android:label="@string/app_n
ame"> <intent-filter>

<action android:name="android.intent.action.MAIN" />

<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>
</application>
</manifest>

Output:

62
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

12. d) Grid View


Layout: Source Code:
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="match_parent"
android:layout_height="match_parent">

<GridView android:numColumns="auto_fit"
android:layout_height="fill_parent"
android:layout_width="match_parent"

android:id="@+id/grid"></GridV
iew> </LinearLayout>

GridActivityDemo.j
ava: package
com.list;

import
android.app.Activity;
import
android.os.Bundle;

import
android.widget.ArrayAdapter;
import android.widget.Gallery;
import
android.widget.GridView;
import
android.widget.ListView;
public class GridActivityDemo extends Activity
{ArrayAdapter<String> aa;

String[]
names={"abc","xyz","abc","xyz","abc","xyz","abc","xyz"};
int[] images={R.drawable.icon, R.drawable.icon,
R.drawable.icon, R.drawable.icon, R.drawable.icon,
R.drawable.icon};

GridView g;

public void onCreate(Bundle


savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
g=(GridView)findViewById(R.id.grid);

63
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

aa=new
ArrayAdapter(this,android.R.layout.simple_list_item
_1,names); g.setAdapter(aa);
}}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>

<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.list" android:versionCode="1"
android:versionName="1.0">

<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon"
android:label="@string/app_name"> <activity
android:name=".GridActivityDemo"

android:label="@string/app_n
ame"> <intent-filter>

<action android:name="android.intent.action.MAIN" />

<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>
</application>
</manifest>Output:

64
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Experiment 13:

Implementation of Android application program that converts the


temperature in Celsius to Fahrenheit

Source Code:
Main.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />

</EditText>
<RadioGroup android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
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="In Celcious" />
<RadioButton android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="In Farhenheat" />
</RadioGroup>

<Button
android:id="@+id/butt
on1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Caluculate"
/>

65
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

<TextView
android:id="@+id/textVie
w1"
android:layout_marginTop="60dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result"

android:textAppearance="?android:attr/textAppearanc
eLarge" /> </LinearLayout>

MainActivity.java:

package
com.convert.convertion;
import
android.app.Activity;
import android.os.Bundle;
import android.view.View;

import
android.view.View.OnClickListener;
import android.widget.Button;

import
android.widget.EditText;
import
android.widget.RadioButton;
import
android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
public class MainActivity extends Activity

{ private TextView tv1; private


RadioGroup rg; private
RadioButton rb1,rb2;
private EditText ed1;
private Button b1;

float
result=0.0f;
String dg="";

protected void onCreate(Bundle


savedInstanceState) {
super.onCreate(savedInstanceState);

66
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText1);
rg=(RadioGroup)findViewById(R.id.radioGroup1);
rb1=(RadioButton)findViewById(R.id.radio0);
rb2=(RadioButton)findViewById(R.id.radio1);
b1=(Button)findViewById(R.id.button1);
tv1=(TextView)findViewById(R.id.textView1);
rg.setOnCheckedChangeListener(new
OnCheckedChangeListener()

{ public void onCheckedChanged(RadioGroup group, int


checkedId)

{ dg=ed1.getText().toString();
if (dg==null)

Toast.makeText(getApplicationContext(), "Enter Some Number",


1111).show();

else
{
switch (checkedId)
{ case R.id.radio0:

float
f1=Float.parseFloat(dg);
result=((f1 - 32) * 5 / 9);

break;
case R.id.radio1:

float
f2=Float.parseFloat(dg);
result=((f2 * 9) / 5) +
32;

break;
}}}});

b1.setOnClickListener(new OnClickListener()
{public void onClick(View v)
{
tv1.setText(""+result);
}
});}}

67
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT
LAB

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

<manifest
xmlns:android="http://schemas.android.com/apk/res/an
droid" package="com.convert.convertion"
android:versionCode="1" android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"/>
<application
android:allowBackup="true"

android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.convert.convertion.MainActivity"
android:label="@string/app_name" >

<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>
</application>
</manifest>

Output:

68
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

Experiment 14:

Implementation of Android application program that


demonstrates intent in mobile application development

Source Code:
Main.xml:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/androi
d" android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffcc00" > <TextView
android:layout_width="wrap_content"

android:textAppearance="?android:attr/textAppearanceL
arge" android:id="@+id/textView1"
android:layout_height="wrap_content"
android:text="FirstClass"></TextView>

<Button android:text="move"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button
> </LinearLayout>

Second.xml;

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

xmlns:android="http://schemas.android.com/apk
/res/android" android:orientation="vertical"
android:layout_width="match_parent"
android:background="#ff0000"
android:layout_height="match_parent">

<TextView android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="@+id/textView1" android:layout_height="wrap_content"
android:text="second class"></TextView>

</LinearLayout>

69
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

IntentDemoActivity.
java: package
com.Demo;

import
android.app.Activity;
import
android.content.Intent;
import
android.os.Bundle;
import
android.view.View;

import
android.view.View.OnClickListener;
import android.widget.Button;
public class IntentDemoActivity extends Activity
{Button move;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

move=(Button)findViewById(R.id.button
1); move.setOnClickListener(new
OnClickListener()

{
public void onClick(View v)
{

Intent i=new
Intent(getApplicationContext(),second.class);

startActivity(i);
}
});
}
}

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

<manifest
xmlns:android="http://schemas.android.com/apk/res/a
ndroid" package="com.Demo"

70
IV BTECH I SEMISTER MOBILE APPLICATION DEVELOPMENT LAB

android:versionCode="1
"
android:versionName="
1.0">

<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon"
android:label="@string/app_name"> <activity
android:name=".IntentDemoActivity"

android:label="@string/app_n
ame"> <intent-filter>

<action android:name="android.intent.action.MAIN" />

<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>

<activity
android:name=".second"></activity>
</application>

</manifest>

Output:

71

You might also like