0% found this document useful (0 votes)
338 views83 pages

Mad Lab Manual

Here are the steps to create a menu in J2ME: 1. Create a MIDlet class that extends MIDlet. 2. Create a Display class object to access the display. 3. Create a ChoiceGroup object to hold the menu options. 4. Add menu options like "Cut", "Copy" etc to the ChoiceGroup. 5. Set the ChoiceGroup as the current display using display.setCurrent(). 6. Handle user selection using ChoiceGroup.addCommand() and override the commandAction() method. 7. Display appropriate messages on selection. Example code: ```java public class MenuMidlet extends MIDlet { Display display
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
338 views83 pages

Mad Lab Manual

Here are the steps to create a menu in J2ME: 1. Create a MIDlet class that extends MIDlet. 2. Create a Display class object to access the display. 3. Create a ChoiceGroup object to hold the menu options. 4. Add menu options like "Cut", "Copy" etc to the ChoiceGroup. 5. Set the ChoiceGroup as the current display using display.setCurrent(). 6. Handle user selection using ChoiceGroup.addCommand() and override the commandAction() method. 7. Display appropriate messages on selection. Example code: ```java public class MenuMidlet extends MIDlet { Display display
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 83

MOBILE APPLICATION DEVELOPMENT LAB

Sri Sarathi Institute of Engineering & Technology

DEPARTMENT OF Computer Science Engineering

MOBILE APPLICATION DEVELOPMENT LAB

IV Year I Semester
MOBILE APPLICATION DEVELOPMENT LAB

LIST OF EXPERIMENTS

Sn Program Title Page No


o
1 Write a J2ME program to show how to change the font
size and colour
2 Write a J2ME program which creates the following kind of
menu.
* cut
* copy
* past
* delete
* select all
* unselect all
3 Create a J2ME menu which has the following options
(Event Handling):
* 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 Create a MIDP 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.
5 Create an MIDP application which examine, that a phone
number, which a user has entered is in the given format
(Input checking):
* Area code should be one of the following: 040, 041, 050,
0400, 044
* There should 6-8 numbers in telephone number (+ area
code)
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.
7 Login to HTTP Server from a J2ME Program. This
J2ME sample program shows how to display a simple
MOBILE APPLICATION DEVELOPMENT LAB
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
8 Write an Android application program that displays Hello
World using Terminal.
9 Write an Android application program that displays Hello
World using Eclipse
10 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.
11 Write an Android application program that demonstrates
the following:
(i) LinearLayout
(ii) RelativeLayout
(iii) TableLayout
(iv) GridView 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
MOBILE APPLICATION DEVELOPMENT LAB

Mobile Application Development (Through J2ME) LABORATORY

Objective:

In this lab, a student is expected to design, implement, document and present a


mobile client/server system using standard Java and Java 2 Micro Edition
(J2ME) platform. Specifically it is required to design and implement a system
that consists mainly of a mobile client (MC) and a Proxy Server (PS). MC will be
written in J2ME, MIDP 2.0, while PS will be written in standard Java. It is
necessary to use a mobile phone emulator to develop and demonstrate the
experiments.

It may be necessary to use other components or existing resources (servers) as


needed. For instance a database local to PS or a web service available on the
Internet that can be invoked by the PS.
MOBILE APPLICATION DEVELOPMENT LAB

Week - 1: Installation of Java Wireless Toolkit (J2ME)

1) If the Java Development Kit (JDK) is not there or only having the Java
Runtime Environment (JRE) installed, install the latest JDK from
http://java.sun.com/javase/downloads/index.jsp. Current stable release of
Java is JDK 6 Update 7 but check the web page in case there are newer non-
beta releases available.

2) Next, download the Java Wireless Toolkit (formerly called J2ME Wireless
Toolkit) from: http://java.sun.com/products/sjwtoolkit/download.html.

3) Run the installer (for example, for Windows it is: sun_java_wireless_toolkit-


2_5_2-windows.exe). The installer checks whether a compatible Java
environment has been pre-installed. If not, it is necessary to uninstall old
versions of Java and perform Step 1 again.

Once after successful installation of Java and the tool kit compile this program
and run the following program in the toolkit.

Steps to run this program in toolkit:

1. Start -> All Programs -> Sun Java Tool Kit -> Wireless Tool Kit

2. Click New Project – Enter Project Name -> Enter Class Name -> Click on
Create Project.

3. Choose appropriate API Selection and Configurations.

4. Place Java Source file in WTK2.1 / WTK2.2\apps\project name\src

5. Build the Project.

6. Run the Project.


MOBILE APPLICATION DEVELOPMENT LAB
Program 1:

Aim:

Write a J2ME program to show how to change the font size and color.

Description:

NetBeans IDE:

• Go to File Menu, Select New Project

• In the “categories” option, select “mobility” option and in the project pin, select
MIDP Application then select next button, then it asks for Project Name. Give the
project name and click next button.

• Now it will ask for default platform selection. Make sure that the emulator
platform is “Sun Java(TM) Wireless tool kit 2.52” for CLDC(Connected Limited
Device Configuration)

• Now click the next button and select the finish button.

• In the central pane select the source pane.

• Go to the projects pane, now press the right most button. Select new
optionMIDlet file. Name it.

• Now click the Finish button.

• In the central pane, remove the source code from the package hello, and copy
your source code from the text file, filename.java

• Now go to the main project, click rightmost button and select the Run option(you
can even select build followed by run).

• Now emulator gets activated.

• Finally launch your program in the emulator and output is displayed on the
emulator.

Canvas class:
The 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.
MOBILE APPLICATION DEVELOPMENT LAB
Program:

package hello;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
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;
//change font
public changeFont(){
myDisplay = Display.getDisplay(this);
decodeCanvas =new DecodeCanvas(this);
}
//brings MIDlet to the active state
public void startApp()throws MIDletStateChangeException {
myDisplay.setCurrent(decodeCanvas);
}
//pauses the MIDlet
public void pauseApp(){
}
//terminates the MIDlet
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){
MOBILE APPLICATION DEVELOPMENT LAB
this.parent = parent;

}
//paints the component
public void paint(Graphics g){
g.setColor(WHITE);
g.fillRect(0, 0, width, height);
Font f1 = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN,
Font.SIZE_LARGE);
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.drawString("MEDIUM FONT", 0, yPos, Graphics.LEFT | Graphics.TOP);
g.setColor(BLACK);
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:
MOBILE APPLICATION DEVELOPMENT LAB
MOBILE APPLICATION DEVELOPMENT LAB
Program 2:

Aim:

Write a J2ME program which creates the following kind of menu.

• Cut

• Copy

• Paste

• Delete

• Select all

• Unselect all

Description:

J2ME

Sun Microsystems defines J2ME as "a highly optimized Java run-time environment
targeting a wide range of consumer products, including pagers, cellular phones,
screen-phones, digital set-top boxes and car navigation systems." J2ME is the
short form for Java 2 Micro Edition. J2ME is meant for tiny devices such as mobile
phones.

MIDP

MIDP is geared toward mobile devices such as cellular phones and pagers. The
MIDP, like KJava, is built upon CLDC and provides a standard run-time
environment that allows new applications and services to be deployed dynamically
on end-user devices.

MIDP contains the following packages:

• Java.lang

• java.io

• java.util

• javax.microedition.io

• javax.microedition.lcdui

• javax.microedition.midlet
MOBILE APPLICATION DEVELOPMENT LAB
• javax.microedition.rms

MIDLET:

A MIDlet is a Java class that extends the javax.microedition.midlet.MIDlet abstract


class. It implements the startApp(), pauseApp(), and destroyApp() methods similar
to J2SE's start(), stop(), and destroy() methods in the java.applet.Applet class.

In addition to the primary MIDlet class that extends


javax.microedition.midlet.MIDlet, an MIDP application usually includes other
classes, which can be packaged as jar files along with their resources -- this is
known as a MIDlet suite.

MIDlet Lifecycle:

A MIDlet has 4 different states: loaded, active, paused, and destroyed.

Loaded: A MIDlet is said to be in loaded state, when it is loaded into the device and
the constructor is called. This is done a bit before when the AMS (Application
Management Software) starts the application by calling the startApp() method.

Active: startApp() method is called to bring the MIDlet in active state. A MIDlet
remains in the active state unless the AMS calls pauseApp() or destroyApp().

Paused: AMS calls pauseApp() method to pauses the MIDlet.

Destroyed: AMS calls desroyApp() method to terminate the MIDlet. Doing so will
release all the resources occupied by the MIDlet.

Program:

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 cmd;
public StringItem st;
//creates reqired menu to display
public MenuCreation()
{
MOBILE APPLICATION DEVELOPMENT LAB
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);
cmd=new Command("Select list item",Command.OK,1);
form=new Form("");
form.append(ch);
form.addCommand(cmd);
form.setCommandListener(this);
st=new StringItem("","");
}//activates the MIDlet
public void startApp() {
display.setCurrent(form);
}
//pauses the MIDlet
public void pauseApp() {
}
//terminates the MIDlet
public void destroyApp(boolean unconditional) {
}
//displays selected actions
public void commandAction(Command command,Displayable displayable)
{
if(command==cmd)
{
MOBILE APPLICATION DEVELOPMENT LAB
st.setText("");
st.setText("your selected option is
"+ch.getString(ch.getSelectedIndex()));
form.append(st);
}
}
}
Output:

Program 3:

Aim:

Create a J2ME menu which has following options(Event Handling).


• Cut – can be on/off
• Copy– can be on/off
• Paste– can be on/off
MOBILE APPLICATION DEVELOPMENT LAB
• Delete– can be on/off
• Select all– put all options on
• Unselect all– put all options off
Description:

Event handling:

High-level MIDP events are divided into two categories: Command and Item events.

1. Command events are triggered by keypresses on the device

2. Item events are the result of visual components changing on the display.

Command objects:

When an event occurs on a mobile device, a Command object holds information


about that event. This information includes:

1. the type of command executed

2. the label of the command

3. priority.

In J2ME, commands are commonly represented with soft-buttons on the device.

Event processing with Command objects: They are

1. Form,

2. TextBox

3. List

4. Canvas.

Item objects

It is also possible to process events using Item objects.For example,

1. the DateField item allows the user to select the date and time that will display on
the screen,

2. theTextField item allows a user to enter a series of alpha-numeric and special


characters.

Event processing with Item objects:


MOBILE APPLICATION DEVELOPMENT LAB
With the exception of StringItem, Spacer, and ImageItem, each Item has the ability
to recognize events. As with a Command object, you must first create a listener
before events will be acknowledged. When a change occurs on a given item -- for
example, the text of a TextField component is updated -- an event is generated.
When a change occurs in any Item component, the method itemStateChanged () will
be called. Within this method you can determine which Item generated the event.

Program:

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
/**
* @Suresh SSIET
*/
public class MenuEvents extends MIDlet implements
CommandListener,ItemStateListener {
//declarations
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;
//events to be displayed in menu
public MenuEvents()
{
display=Display.getDisplay(this);
form=new Form("");
form1=new Form("Selcted Options are");
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);
MOBILE APPLICATION DEVELOPMENT LAB
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);
}//activates the MIDlet
public void startApp() {
display.setCurrent(form);
}
//pauses the MIDlet
public void pauseApp() {
}
//terminates the MIDlet
public void destroyApp(boolean unconditional) {
}
//indicates that command event has occurred on displayable
public void commandAction(Command command,Displayable displayable)
{
if(displayable==form)
{
if(command==View)
{
boolean opt[]=new boolean[ch.size()];
options=new StringItem("","");
String values="";
ch.getSelectedFlags(opt);
options.setText("");
for(int i=0;i<opt.length;i++)
{
if(opt[i])
{
values+=ch.getString(i)+"\n";
}
}
MOBILE APPLICATION DEVELOPMENT LAB
options.setText(values);
form1.append(options);
display.setCurrent(form1);
}
else if(command==Exit)
{
destroyApp(true);
notifyDestroyed();
}
}
else if(displayable==form1)
{
if(command==Back)
{
display.setCurrent(form);
options.setText("");
}
}
}
public void itemStateChanged(Item item)
{
if(item==ch1)
{
int i=0;
int size=ch.size();
while(i<size)
{
if(ch1.getSelectedIndex()==0)
ch.setSelectedIndex(i, true);
else
ch.setSelectedIndex(i, false);
i++;
}
}
}
}

Output:
MOBILE APPLICATION DEVELOPMENT LAB

Program 4:

Aim:

Create a MIDP 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.

Description:

Display object:

A MIDlet has one instance of a Display object. This object is used to obtain
information about the current display -- such as the color support available -- and
includes methods for requesting that objects (that is, Form s and Textbox es) be
displayed. The Display object is essentially the manager of the device display,
controlling what is shown on the device.

Displayable object:

Although there is only one Display object per MIDlet, many objects within a MIDlet
may be displayable -- that is, Forms, TextBoxes, ChoiceGroups, etc. A Displayable
object is a component that is visible on a device. MIDP contains two subclasses of
Displayable: Screen and Canvas. Following are the class definitions for each:

• abstract public class Displayable

• public abstract class Canvas extends Displayable


MOBILE APPLICATION DEVELOPMENT LAB
• public abstract class Screen extends Displayable

Screen object:

A Screen object is not something that is visible on the device. Rather, Screen is
subclassed by high-level components, which the end-user then interacts with on
the display.

Form and Item components:

A Form is essentially a container to hold other components, where each component


is a subclass of the Item class. Some of the device-display components that
comprise MIDP's high-level API are:

• DateField
• Gauge
• StringItem
• TextField
• ChoiceGroup
• Spacer
• CustomItem
• Image and ImageItem
The TextField component:

A Textfield is analogous to any typical text entry field. You can specify a label, the
maximum number of characters, and the type of data you will accept. The TextField
component also implements a password modifier that masks characters as they are
input. The constructor for TextField:

TextField(String label, String text, intmaxSize, int constraints)

The final parameter, constraints, is to specify the type of input allowed in the
TextField.

Program:

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class BarGraphMIDlet extends MIDlet implements CommandListener{
//Declarations
public Form form;
public Command exitCommand;
MOBILE APPLICATION DEVELOPMENT LAB
public Command OkCommand;
public Command backCommand;
public Displayable d;
public Display display;
public TextField textfield1;
public TextField textfield2;
public TextField textfield3;
public TextField textfield4;
//displays bar graph of given text fields
public BarGraphMIDlet()
{
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);
form.append(textfield1);
form.append(textfield2);
form.append(textfield3);
form.append(textfield4);
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);
}//activates the MIDlet
public void startApp() {
display.setCurrent(form);
}
//pauses the MIDlet
public void pauseApp() {
}
//terminates the MIDlet
public void destroyApp(boolean unconditional) {
}

//indicates that command event has occurred on displayable


public void commandAction(Command command,Displayable displayable)
{
MOBILE APPLICATION DEVELOPMENT LAB
if(displayable==form)
{
if(command==OkCommand)
{
int[] data=new int[4];
//parses the string argument and returns an integer
data[0]=Integer.parseInt(textfield1.getString());
data[1]=Integer.parseInt(textfield2.getString());
data[2]=Integer.parseInt(textfield3.getString());
data[3]=Integer.parseInt(textfield4.getString());
d=new BarCanvas(data);
d.addCommand(backCommand);
d.setCommandListener(this);
display.setCurrent(d);
}
else if(command==exitCommand)
notifyDestroyed();
}
else if(displayable==d)
{
if(command==backCommand)
display.setCurrent(form);
}

}
}

class BarCanvas extends Canvas{

int[] data;
public int x;
public int y;
public int y1;
public int h;
public BarCanvas(int[] data)
{
this.data=data;
x=10;
}
public void paint(Graphics g)
{
MOBILE APPLICATION DEVELOPMENT LAB
g.setColor(255, 255, 255);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(255, 125, 100);
int i=0;
y1=data[0];
h=200;
while(i<data.length)
{
y=data[i];
h=200+y1-y;
g.fillRect(x, y,25 , h);
x+=30;
i++;
}
}
}
Output:
MOBILE APPLICATION DEVELOPMENT LAB
Program 5:

Aim:

Create an MIDP application which examine, that a phone number, which a user
has entered is in the givcen format(Input checking):

• Area code should be one of the following: 040, 041, 050, 0400, 044

• There should 6-8 numbers in the telephone number(+area code)

Description:

The TextField component

A Textfield is analogous to any typical text entry field. You can specify a label, the
maximum number of characters, and the type of data you will accept. The TextField
component also implements a password modifier that masks characters as they are
input. The constructor for TextField:

TextField(String label, String text, intmaxSize, int constraints)

The final parameter, constraints, is to specify the type of input allowed in the
TextField.

TextField constraints

MIDP defines the following constraint parameters for the TextField component:

Adding a new constraint:

Here's the original TextField:

tfText = new TextField("Phone:","",10, TextField.PHONENUMBER);

tfText = new TextField("Phone:","",10, TextField.PHONENUMBER |


TextField.PASSWORD);

• ANY allows any characters.

• EMAILADDR allows only valid email addresses.

• NUMERIC allows any numeric value.

• PHONENUMBER allows only phone numbers.

• URL allows only characters that are valid within URL.

• PASSWORD masks all characters as they are input.


MOBILE APPLICATION DEVELOPMENT LAB
• The ChoiceGroup component

• ChoiceGroup components allow a user to select from a predefined list of entries.


There are two ChoiceGroup formats: multi-selection, which are commonly referred
to as checkboxes and exclusive-selection, which are essentially radio groups.

Program:

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class InputChecking extends MIDlet implements CommandListener {
public Form form1;
public TextField textfield1;
public Command exitCommand;
public Command okCommand;
public StringItem st;
public Display display;
//checks the input fields entered for validation
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);
}
//activates the MIDlet
public void startApp() {
display.setCurrent(form1);
}
//pauses the MIDlet
public void pauseApp() {
}
//terminates the MIDlet
public void destroyApp(boolean unconditional) {
}
//indicates that command event has occurred on displayable
public void commandAction(Command cmd,Displayable displayable)
MOBILE APPLICATION DEVELOPMENT LAB
{
if(cmd==exitCommand)
notifyDestroyed();
else if(cmd==okCommand)
{
String s=textfield1.getString();
s=s.replace(' ', '.');
int len=s.length();
int i=0;
int c=0;
String s1="";
while(i<len)
{
if(s.charAt(i)=='.')
{
if(c==0)
{

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)
MOBILE APPLICATION DEVELOPMENT LAB
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:

Program6:

Aim:

Write a sample program to show how to make to make a SOCKET connection from
J2ME phone. Many a times there is a need to connect backend HTTP server from
MOBILE APPLICATION DEVELOPMENT LAB
the J2ME application. Show how to make a SOCKET connection from the phone to
port 80.

Description:

The J2ME applications can be used to do many useful things. A few of the
capabilities of a J2ME program are

• Making UDP connections back to the server or communication between a two.


• Making HTTP connections back to a HTTP server to make rich applications
• Making Socket connections
• Bar Code scanning
• Bluetooth programming
javax.microedition.io helper interfaces:

In addition to the generic connection factory class, the javax.microedition.io


package also contains the following connection-oriented interfaces:

• Connection -- Defines the most basic type of connection. This interface is also
the base class for all other connection interfaces in this package.

• ContentConnection -- Defines a stream connection over which content is passed.

• InputConnection -- Defines a generic input stream connection and the


capabilities that it must support.

• OutputConnection -- Defines a generic output stream connection and the


capabilities that it must support.

• StreamConnection -- Defines a generic stream connection and the capabilities


that it must support.

• StreamConnectionNotifier -- Defines the capabilities that a stream connection


notifier must have.

Program:

import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
MOBILE APPLICATION DEVELOPMENT LAB
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class SocketMIDlet extends MIDlet


implements CommandListener, Runnable {

private Display display;


private Form addressForm;
private Form connectForm;
private Form displayForm;
private TextField serverName;
private TextField serverPort;
private StringItem messageLabel;
private StringItem errorLabel;
private Command okCommand;
private Command exitCommand;
private Command backCommand;

protected void startApp() throws MIDletStateChangeException {


if (display == null) {
initialize();
display.setCurrent(addressForm);
}
}

protected void pauseApp() {


}

protected void destroyApp(boolean unconditional)


throws MIDletStateChangeException {
}

//indicates that command event has occurred on displayable


public void commandAction(Command cmd, Displayable d) {
MOBILE APPLICATION DEVELOPMENT LAB
if (cmd == okCommand) {
Thread t = new Thread(this);
t.start();
display.setCurrent(connectForm);
} else if (cmd == backCommand) {
display.setCurrent(addressForm);
} else if (cmd == exitCommand) {
try {
destroyApp(true);
} catch (MIDletStateChangeException ex) {
}
notifyDestroyed();
}
}

public void run() {


InputStream is = null;
OutputStream os = null;
StreamConnection socket = null;

try {
String server = serverName.getString();
String port = serverPort.getString();
String name = "socket://" + server + ":" + port;
socket = (StreamConnection)Connector.open(name, Connector.READ_WRITE);
} catch (Exception ex) {
Alert alert = new Alert("Invalid Address",
"The supplied address is invalid\n" +
"Please correct it and try again.", null,
AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert, addressForm);
return;
}

try {
// Send a message to the server
String request = "GET / HTTP/1.0\n\n";

os = socket.openOutputStream();
MOBILE APPLICATION DEVELOPMENT LAB
os.write(request.getBytes());
os.close();

// Read the server's reply, up to a maximum


// of 128 bytes.
is = socket.openInputStream();
final int MAX_LENGTH = 128;
byte[] buf = new byte[MAX_LENGTH];
int total = 0;
while (total < MAX_LENGTH) {
int count = is.read(buf, total, MAX_LENGTH - total);
if (count < 0) {
break;
}
total += count;
}
is.close();
String reply = new String(buf, 0, total);
messageLabel.setText(reply);
socket.close();
display.setCurrent(displayForm);
} catch (IOException ex) {
Alert alert = new Alert("I/O Error",
"An error occurred while communicating with the server.",
null, AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert, addressForm);
return;
} finally {
// Close open streams and the socket
try {
if (is != null) {
is.close();
is = null;
}
} catch (IOException ex1) {
}
try {
if (os != null) {
os.close();
os = null;
MOBILE APPLICATION DEVELOPMENT LAB
}
} catch (IOException ex1) {
}
try {
if (socket != null) {
socket.close();
socket = null;
}
} catch (IOException ex1) {
}
}
}

private void initialize() {


display = Display.getDisplay(this);

// Commands
exitCommand = new Command("Exit", Command.EXIT, 0);
okCommand = new Command("OK", Command.OK, 0);
backCommand = new Command("Back", Command.BACK, 0);

// The address form


addressForm = new Form("Socket Client");
serverName = new TextField("Server name:", "", 256, TextField.ANY);
serverPort = new TextField("Server port:", "", 8, TextField.NUMERIC);
addressForm.append(serverName);
addressForm.append(serverPort);
addressForm.addCommand(okCommand);
addressForm.addCommand(exitCommand);
addressForm.setCommandListener(this);

// The connect form


connectForm = new Form("Connecting");
messageLabel = new StringItem(null, "Connecting...\nPlease wait.");
connectForm.append(messageLabel);
connectForm.addCommand(backCommand);
connectForm.setCommandListener(this);

// The display form


displayForm = new Form("Server Reply");
messageLabel = new StringItem(null, null);
MOBILE APPLICATION DEVELOPMENT LAB
displayForm.append(messageLabel);
displayForm.addCommand(backCommand);
displayForm.setCommandListener(this);
}
}
Output:

Program 7:

Aim:

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.

Description:
MOBILE APPLICATION DEVELOPMENT LAB
There are three other types of screens: alerts (amessage dialog that flashes on the
display), forms (a control panel containing control itemssuch as labels, text fields,
and buttons), and lists.

JSP:

JavaServer Pages (JSP) is a technology that helps software developers create


dynamically generated web pages based on HTML,XML, or other document types.
To deploy and run JavaServer Pages, a compatible web server with a servlet
container, such as Apache Tomcat or Jetty, is required.

Example that loads the driver and establish a connection with MySql database.

Class.forName("com.mysql.jdbc.Driver");

onnection con=null;

con=DriverManager.getConnection("jdbc:mysql://localhost/student");

All the Methods of DriverManager class are static

Creation of Login Table:

1. Start-> Oracle Development Kit -> SQL Plus

Login Credentials: Username: Scott Password: Tiger Host String: Orcl


MOBILE APPLICATION DEVELOPMENT LAB

2. Create a table Login with two attributes name and password

3. Description of Table to verify the attributes


MOBILE APPLICATION DEVELOPMENT LAB

4.Insert the records of User Login credentials

To provide dynamic input, we can also use & before the variables

5. Retrieve all records of the Login table


MOBILE APPLICATION DEVELOPMENT LAB

Program:

Java code:

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public Form form1;
public Command okCommand;
public Display display;
public HttpConnection ht=null;
public InputStream ist=null;
public StringItem st;
public TextField t1;
public TextField t2;
public Alert alert;
public Form form2;
public login()
{
display=Display.getDisplay(this);
st=new StringItem(" "," Welcome");
alert =new Alert(" ","Wrong UserName or Password",null,AlertType.INFO);

t1=new TextField("UserName"," ",30,TextField.ANY);


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);
MOBILE APPLICATION DEVELOPMENT LAB
form1.append(t1);
form1.append(t2);
form2.append(st);
}

publicvoid startApp(){
display.setCurrent(form1);
}

publicvoid pauseApp(){
}

publicvoid destroyApp(boolean unconditional){


notifyDestroyed();
}
publicvoid commandAction(Command cmd,Displayable d)
{
if(cmd==okCommand)
{
try
{

// 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/WebApplication
7/index.jsp");
ht=(HttpConnection)Connector.open(url);
ist=ht.openInputStream();
byte[] b=newbyte[900];
ist.read(b);
String s=new String(b);
s=s.trim();
if(s.equals("ok"))
display.setCurrent(form2);
else
{

alert.setTimeout(Alert.FOREVER);
MOBILE APPLICATION DEVELOPMENT LAB
display.setCurrent(alert);
}
}
catch(Exception ex)
{
form1.append(ex.toString());
}
}
}
}

JSP page:
<%--
PVPSIT
--%>

<%@page import="java.sql.*" %>

<%
String Htno=request.getParameter("t1");
String Sname=request.getParameter("t2");
String sql="select * from stu where sno="+"'"+Htno+"'"+" and
sname="+"'"+Sname+"'";

try
{

Class.forName("com.mysql.jdbc.Driver");
Connection
cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/std","root","anurag"
);
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery(sql);
if(rs.next())
{
out.println("ok");
out.close();
}
else
{
out.println("0");
MOBILE APPLICATION DEVELOPMENT LAB
out.close();
}
}
catch(Exception ex)
{
out.println(ex.toString());
out.close();
}
out.close();

%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
</body>
</html>

Output:
MOBILE APPLICATION DEVELOPMENT LAB

Program 8:

Aim:

Write an android application program that displays Hello World using Terminal.
MOBILE APPLICATION DEVELOPMENT LAB
Description:

Android Applications:

Android applications are written in the Java programming language. The Android
SDK tools compile the code—along with any data and resource files—into an
Android package, an archive file with an .apksuffix. All the code in a single .apk file
is considered to be one application and is the file that Android-powered devices use
to install the application.

• Android applications are composed of one or more application components


(activities, services, content providers, and broadcast receivers)

• Each component performs a different role in the overall application behavior,


and each one can be activated individually (even by other applications)

• The Android operating system is a multi-user Linux system in which each


application is a different user.

• Each process has its own virtual machine (VM), so an application's code runs in
isolation from other applications.

Processing Steps:

Pre-requirements: you need to add sdk/platform-tools to environment variables and


add ant & java to the system variables.
MOBILE APPLICATION DEVELOPMENT LAB
1)Go to SDK/tools.

2)Hold shift and right click in this folder, click on open command window from
here.
MOBILE APPLICATION DEVELOPMENT LAB

3)Type android create project –target 1 –name TermHelloWorld –path ./Android –


activity MyAndroidActivity1 –package com.pvpsit.myandroid1

4) Now type the command android avdand follow the steps as described in the
screenshot.
MOBILE APPLICATION DEVELOPMENT LAB

5)Click on start after the creation


MOBILE APPLICATION DEVELOPMENT LAB

6)Identify the project folder Android and move to the directory


MOBILE APPLICATION DEVELOPMENT LAB

7)Open the command window by holding shift key and right click

8)Now type the command ant debug, You will get


MOBILE APPLICATION DEVELOPMENT LAB

9) Now type adb install bin/TermHelloWorld-debug.apk you should get.


MOBILE APPLICATION DEVELOPMENT LAB
MOBILE APPLICATION DEVELOPMENT LAB
Program 9:

Aim:

Write an android application program that displays Hello World using Eclipse.

Description:

Android applications can be easily developed using Eclipse (Android's official


development platform) with the help of a plug-in called Android Development Tools
(ADT).

Google provides a packaged and configured Android development environment


based on the Eclipse IDE called Android Developer Tools. Under the following URL
you find an archive file which includes all required tools for Android development:
Getting the Android SDK.

An Android application declares the required permissions in its


AndroidManifest.xml configuration file.

System requirements:

Before beginning Android development, please make sure you have the following
installed:

• Eclipse SDK : V3.5 is suggested for use with the latest Android SDK. This can
be downloaded from the Galileo download page.

• Android SDK: For developers, Android SDK provides a rich set of tools,
including debugger, libraries, handset emulator, documentation, sample code, and
tutorials

• Android Development Tools (ADT) : This is an Eclipse plug-in. It is the


equivalent of JDT (Java Development Tools) for Android Development.

Processing Steps:

1)start eclipse and set an workspace.


MOBILE APPLICATION DEVELOPMENT LAB

2)start a new android project.

3)The following screens shall come.[note: it varies with eclipse versions].


MOBILE APPLICATION DEVELOPMENT LAB
MOBILE APPLICATION DEVELOPMENT LAB

4) hello world is default text. We can directly run it without editing our java source
file.
MOBILE APPLICATION DEVELOPMENT LAB
MOBILE APPLICATION DEVELOPMENT LAB
MOBILE APPLICATION DEVELOPMENT LAB

Program 10:
MOBILE APPLICATION DEVELOPMENT LAB
Aim:

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

Description:

Android applications can be easily developed using Eclipse (Android's official


development platform) with the help of a plug-in called Android Development Tools
(ADT).

This program includes folders named assets, properties, and resources, bin, libs,
gen, res. It also includes source file which will be in java. Manifestation file which is
an xml document. An Android application declares the required permissions in its
AndroidManifest.xml configuration file. Classpath is to be set.When it is executed it
accepts a name from the user and displays the hello name to the user in response
as output from Eclipse.

Program:

package com.example.pvpprog11;

import android.os.Bundle;
import android.app.Activity;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import android.view.*;
Public class MainActivity extends Activity {
EditText in;
TextView disp;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MOBILE APPLICATION DEVELOPMENT LAB
setContentView(R.layout.activity_main);
in=(EditText)findViewById(R.id.editText1);
disp=(TextView)findViewById(R.id.textView1);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new Click());
}
class Click implements OnClickListener
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==b1)
{
String name=in.getText().toString();
disp.setText("Hello\t"+name);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

Output:
MOBILE APPLICATION DEVELOPMENT LAB

Program 11:

Aim:
MOBILE APPLICATION DEVELOPMENT LAB
Write an Android Application Program that demonstrate the following.

(i) LinearLayout

(ii) RelativeLayout

(iii) TableLayout

(iv) GridLayout

Description:

This program shows how you can design the android application using different
layouts. This program includes folders named assets, properties, and resources,
bin, libs, gen, res. It also includes source file which will be in java. Manifestation file
which is an xml document. An Android application declares the required
permissions in its AndroidManifest.xml configuration file. Classpath is to be
set.When it is executed it displays the information in various different types of
Layouts.

LinearLayout: In a linear layout, like the name suggests, all the elements are
displayed in a linear fashion(below is an example of the linear layouts),
either Horizontally or Vertically and this behavior is set
in android:orientation which is an attribute of the node LinearLayout.

package com.example.androidlayouts;

import android.app.Activity;

import android.os.Bundle;

public class AndroidLayoutsActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.linear_layout);
MOBILE APPLICATION DEVELOPMENT LAB
}

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

<!-- Parent linear layout with vertical orientation -->

<LinearLayout

xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="match_parent"

android:layout_height="match_parent">

<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"

android:text="Email:" android:padding="5dip"/>

<EditText android:layout_width="fill_parent"
android:layout_height="wrap_content"

android:layout_marginBottom="10dip"/>

<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"

android:text="Login"/>

<!-- Child linear layout with horizontal orientation -->

<LinearLayout android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:orientation="horizontal" android:background="#2a2a2a"
MOBILE APPLICATION DEVELOPMENT LAB
android:layout_marginTop="25dip">

<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"

android:text="Home" android:padding="15dip" android:layout_weight="1"

android:gravity="center"/>

<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"

android:text="About" android:padding="15dip" android:layout_weight="1"

android:gravity="center"/>

</LinearLayout>

</LinearLayout>
MOBILE APPLICATION DEVELOPMENT LAB
OUTPUT:

2. Relative Layout
In a relative layout every element arranges itself relative to other elements or a
parent element.
As an example, lets consider the layout defined below. The “ Cancel ” button is
placed relatively, to the right of the “ Login ” button parallely . Here is the code
snippet that achieves the mentioned alignment (Right of Login button parallely)

Program:
XML PROGRAM:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"
MOBILE APPLICATION DEVELOPMENT LAB
android:layout_height="wrap_content">

<TextView android:id="@+id/label" android:layout_width="fill_parent"

android:layout_height="wrap_content" android:text="Email" />

<EditText android:id="@+id/inputEmail" android:layout_width="fill_parent"

android:layout_height="wrap_content"
android:layout_below="@id/label" />

<Button android:id="@+id/btnLogin" android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:layout_below="@id/inputEmail"

android:layout_alignParentLeft="true"
android:layout_marginRight="10px"

android:text="Login" />

<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:layout_toRightOf="@id/btnLogin"

android:layout_alignTop="@id/btnLogin" android:text="Cancel" />

<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:layout_alignParentBottom="true" android:text="Register new Account"

android:layout_centerHorizontal="true"/>

</RelativeLayout>
OUTPUT:
MOBILE APPLICATION DEVELOPMENT LAB

3. Table Layout

Table layouts in Android works in the same way HTML table layouts work. You
can divide your layouts into rows and columns . Its very easy to understand.
The image below should give you an idea.

Program:
MainActivity.java:
MOBILE APPLICATION DEVELOPMENT LAB
package com.example.tablelayout;

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

public class MainActivity extends Activity


{

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

activity_main.xml:

<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shrinkColumns="*"
android:stretchColumns="*"
android:background="#ffffff">
<TableRow
android:id="@+id/tableRow1"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:id="@+id/TextView1"
android:text="SNO"
android:layout_weight="1"
android:background="#dcdcdc"
android:textColor="#000000"
android:padding="20dip"
android:gravity="center"/>
<TextView
android:id="@+id/TextView1"
MOBILE APPLICATION DEVELOPMENT LAB
android:layout_weight="1"
android:background="#d3d3d3"
android:gravity="center"
android:padding="20dip"
android:text="Name"
android:textColor="#000000" />
<TextView
android:id="@+id/TextView1"
android:text="Marks"
android:layout_weight="1"
android:background="#cac9c9"
android:textColor="#000000"
android:padding="20dip"
android:gravity="center"/>
</TableRow>
<TableRow
android:id="@+id/tableRow1"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:id="@+id/TextView1"
android:text="1"
android:layout_weight="1"
android:background="#dcdcdc"
android:textColor="#000000"
android:padding="20dip"
android:gravity="center"
/>
<TextView
android:id="@+id/TextView1"
android:layout_weight="1"
android:background="#d3d3d3"
android:gravity="center"
android:padding="20dip"
android:text="ABC"
android:textColor="#000000" />
<TextView
android:id="@+id/TextView1"
android:text="95"
android:layout_weight="1"
android:background="#cac9c9"
android:textColor="#000000"
android:padding="20dip"
android:gravity="center"/>
</TableRow>
</TableLayout>
OUTPUT:
MOBILE APPLICATION DEVELOPMENT LAB

(4) GridViewLayout:

Program:

MainActivity.java:

package com.example.gridlayout;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
MOBILE APPLICATION DEVELOPMENT LAB
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity 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.activity_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()
{
@Override
public void onItemClick(AdapterView<?> parent, View v,int position,
long id)
{
Toast.makeText(getApplicationContext(),((TextView) v).getText() ,
Toast.LENGTH_SHORT).show();
}
});
}
}

activity_main.xml:
MOBILE APPLICATION DEVELOPMENT LAB
<RelativeLayout
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<GridView
android:id="@+id/gridview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="50dp"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" >
</GridView>
</RelativeLayout>

OUTPUT:

Program 12:
MOBILE APPLICATION DEVELOPMENT LAB
Aim:

Write an Android Application Program that converts the temperature in


Celsius to Fahrenheit.

Description:

This program shows how you can convert temperature from Celsius to Fahrenheit.

This program includes folders named assets, properties, and resources, bin, libs,
gen, res. It also includes source file which will be in java. Manifestation file which is
an xml document. An Android application declares the required permissions in its
AndroidManifest.xml configuration file. Classpath is to be set.When it is executed it
displays the temperature in Fahrenheit taking the temperature in Celsius as input.

Program:

package com.example.gecprog13;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;

public class MainActivity extends Activity {


TextView disp;
EditText in;
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
disp=(TextView)findViewById(R.id.textView2);
in=(EditText)findViewById(R.id.editText1);
b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new Click());
MOBILE APPLICATION DEVELOPMENT LAB
}
class Click implements OnClickListener
{
int cel;
int far;
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==b)
{
cel=Integer.parseInt(in.getText().toString());
far=((cel * 9) / 5) + 32;
disp.setText("Temperature in Fahrenheit is\t"+far);

}
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

Output:
MOBILE APPLICATION DEVELOPMENT LAB

Program 13:

Aim:

Write an Android Application Program that demonstrates intent in mobile


application development.
MOBILE APPLICATION DEVELOPMENT LAB
Description:

This program shows how you can intent in mobile application development. In this
program there are two activities - IntentActionDemo.java and IntentA.java that both
extend the super class Activity. Do not forget to declare any new activity in the
AndroidManifest.xml with permission.

I have introduced buttons in both activities which have a listener to allow an intent
to transition from one intent to the other activity and vis-versa.
Simple intent example;
Note that optional step 2 was not used in our demo.
Step 1: Intent i = new Intent(context, NameOfClassToTransitionTo.class)

Step 2:(Optional)Intents can take various forms that make it even carry data in
key/name pairs ie i.putExtra("key1", "My first Info")
i.putExtra("key2", "My second Info")

Step 3: startActivity(i)

Program:

IntentActionDemo.java

Code:

package com.thenewcircle.com;

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 IntentActionDemo extends Activity implements OnClickListener

{
/** Called when the activity is first created. */
MOBILE APPLICATION DEVELOPMENT LAB
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button button = (Button) findViewById(R.id.intentButton);


button.setOnClickListener(this);

@Override
public void onClick(View src) {
Intent i = new Intent(this, IntentA.class);
startActivity(i);
}
}

IntentA.java

Code:
package com.thenewcircle.com;

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 IntentA extends Activity implements OnClickListener{

@Override
public void onClick(View src) {
Intent i = new Intent(this, IntentActionDemo.class);
startActivity(i);
}

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.intenta);

Button button = (Button) findViewById(R.id.ButtonIntentA);


MOBILE APPLICATION DEVELOPMENT LAB
button.setOnClickListener(this);
}
}

AndroidManifest.xml
Code:

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.thenewcircle.com"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name=".IntentActionDemo"
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="IntentA"></activity>
</application>
<uses-sdk android:minSdkVersion="3" />

</manifest>

string.xml

Code:

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


<resources>
<string name="hello">Hello</string>
<string name="app_name">IntentActionDemo</string>
<string name="IntentA">Click Next intent</string>
<string name="world">World!</string>
<string name="Intent0">Click to Previous Intent</string>
</resources>

main.xml
Code:

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
MOBILE APPLICATION DEVELOPMENT LAB
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"
android:textSize="18sp"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/intentButton"
android:text="@string/IntentA"></Button>
</LinearLayout>

intenta.xml
Code:

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


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

<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/TextViewWorld"
android:text="@string/world" android:textSize="18sp"></TextView>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/ButtonIntentA"
android:text="@string/Intent0"></Button>
</LinearLayout>

Screenshot
MOBILE APPLICATION DEVELOPMENT LAB
MOBILE APPLICATION DEVELOPMENT LAB
Additional Programs:

Program 1:

Aim: Write a J2me program to check the given phone is a color phone or not.

Program:

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class checkcolor extends MIDlet implements CommandListener
{
private Display display;
private Form form;
private TextBox textbox;
private Command exit;
public checkcolor()
{
display=Display.getDisplay(this);
exit=new Command("EXIT",Command.SCREEN,1);
String msg=null;
if(display.isColor())
{
msg="color display";
}
Else
{
msg="No color display";
}
textbox=new TextBox("check colors",msg,17,0);
textbox.addCommand(exit);
textbox.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(textbox);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
notifyDestroyed();
}
public void commandAction(Command command,Displayable displayable)
{
if(command==exit)
{
MOBILE APPLICATION DEVELOPMENT LAB
destroyApp(true);
notifyDestroyed();
}
}
}

OUTPUT:
MOBILE APPLICATION DEVELOPMENT LAB

Program 2:

Aim: Write a J2me program to check the given color is right color or not

Program:

/*Radio Buttons*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class RadioButtons extends MIDlet implements ItemStateListener,
CommandListener {
private Display display;
private Form form;
private Command exit;
private Item selection;
private ChoiceGroup radioButtons;
private int defaultIndex;
private int radioButtonsIndex;
public RadioButtons(){
display = Display.getDisplay(this);
radioButtons = new ChoiceGroup( "Select Your Color", Choice.EXCLUSIVE);
MOBILE APPLICATION DEVELOPMENT LAB
radioButtons.append("Red", null);
radioButtons.append("White", null);
radioButtons.append("Blue", null);
radioButtons.append("Green", null);
defaultIndex = radioButtons.append("All", null);
radioButtons.setSelectedIndex(defaultIndex, true);
exit = new Command("Exit", Command.EXIT, 1);
form = new Form("");
radioButtonsIndex = form.append(radioButtons);
form.addCommand(exit);
form.setCommandListener(this);
form.setItemStateListener(this);
}
public void startApp(){ display.setCurrent(form);}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command command,
Displayable displayable)
{
if (command == exit)
{
destroyApp(true);
notifyDestroyed();
}
}
public void itemStateChanged(Item item)
{
if (item == radioButtons)
{
StringItem msg = new StringItem("Your color is ",
radioButtons.getString(radioButtons.getSelectedIndex()));
form.append(msg);
}
}
}
MOBILE APPLICATION DEVELOPMENT LAB

Output
MOBILE APPLICATION DEVELOPMENT LAB

Output:

You might also like