Mad Lab Manual
Mad Lab Manual
IV Year I Semester
MOBILE APPLICATION DEVELOPMENT LAB
LIST OF EXPERIMENTS
development
MOBILE APPLICATION DEVELOPMENT LAB
Objective:
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.
Once after successful installation of Java and the tool kit compile this program
and run the following program in the 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.
Aim:
Write a J2ME program to show how to change the font size and color.
Description:
NetBeans IDE:
• 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.
• Go to the projects pane, now press the right most button. Select new
optionMIDlet file. Name it.
• 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).
• 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;
}
//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);
Output:
MOBILE APPLICATION DEVELOPMENT LAB
MOBILE APPLICATION DEVELOPMENT LAB
Program 2:
Aim:
• 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.
• Java.lang
• java.io
• java.util
• javax.microedition.io
• javax.microedition.lcdui
• javax.microedition.midlet
MOBILE APPLICATION DEVELOPMENT LAB
• javax.microedition.rms
MIDLET:
MIDlet Lifecycle:
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().
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:
Event handling:
High-level MIDP events are divided into two categories: Command and Item events.
2. Item events are the result of visual components changing on the display.
Command objects:
3. priority.
1. Form,
2. TextBox
3. List
4. Canvas.
Item objects
1. the DateField item allows the user to select the date and time that will display on
the screen,
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:
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.
• 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:
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) {
}
}
}
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
Description:
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:
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:
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)
{
}
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
• Connection -- Defines the most basic type of connection. This interface is also
the base class for all other connection interfaces in this package.
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;
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();
// Commands
exitCommand = new Command("Exit", Command.EXIT, 0);
okCommand = new Command("OK", Command.OK, 0);
backCommand = new Command("Back", Command.BACK, 0);
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:
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");
To provide dynamic input, we can also use & before the variables
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);
publicvoid startApp(){
display.setCurrent(form1);
}
publicvoid pauseApp(){
}
// 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
--%>
<%
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.
• Each process has its own virtual machine (VM), so an application's code runs in
isolation from other applications.
Processing Steps:
2)Hold shift and right click in this folder, click on open command window from
here.
MOBILE APPLICATION DEVELOPMENT LAB
4) Now type the command android avdand follow the steps as described in the
screenshot.
MOBILE APPLICATION DEVELOPMENT LAB
7)Open the command window by holding shift key and right click
Aim:
Write an android application program that displays Hello World using Eclipse.
Description:
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
Processing Steps:
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:
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;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.linear_layout);
MOBILE APPLICATION DEVELOPMENT LAB
}
XML FILE:
<?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">
<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"/>
<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:gravity="center"/>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
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">
android:layout_height="wrap_content"
android:layout_below="@id/label" />
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"
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
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;
@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;
@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:
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.*;
}
}
}
@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:
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;
{
/** Called when the activity is first created. */
MOBILE APPLICATION DEVELOPMENT LAB
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
@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;
@Override
public void onClick(View src) {
Intent i = new Intent(this, IntentActionDemo.class);
startActivity(i);
}
AndroidManifest.xml
Code:
<activity android:name="IntentA"></activity>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
string.xml
Code:
main.xml
Code:
intenta.xml
Code:
<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: