Académique Documents
Professionnel Documents
Culture Documents
S.No
1.
2.
3.
4.
5.
Date
Experiment Name
1. Write a J2ME program to show
how to change the font size and
color.
2. Write a J2ME program which
creates the following kind of
menu.
* cut
* copy
* paste
* 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)
Page.
No
Marks
Remarks
6.
7.
8.
9.
10.
11.
12.
13.
14.
What is J2ME?
J2ME is the short form for Java 2 Micro Edition. J2ME is meant for small devices such as
mobile phones, TV set top boxes, Vehicle telemetric, pagers, PDAs etc.
There are many differences between J2ME and other Editions of Java. The reason being the
target devices of J2ME are very much different from the Computers.
Some of the main differences between computers and the J2ME devices are:
Page 3
Small display
Less Battery power
Limited connectivity to internet
Types of configurations in J2ME:A configuration defines the minimum Java technology that an application developer can
expect on a broad range of implementing devices.
J2ME currently defines two configurations:
1. Connected Limited Device Configuration (CLDC)
2. Connected Device Configuration (CDC)
1) Connected Limited Device Configuration (CLDC): Specifies the Java environment for mobile phone, pager and wireless devices
CLDC devices are usually wireless
160 - 512k of memory available for Java
Typically has limited power or battery operated
Network connectivity, often wireless, intermittent, low-bandwidth (9600bps or less)
2) Connected Device Configuration (CDC): Describes the Java environment for digital television set-top boxes, high end wireless
devices and automotive telemetric systems.
Device is powered by a 32-bit processor
2MB or more of total memory available for Java
Network connectivity, often wireless, intermittent, low-bandwidth (9600bps or less)
Types of Profiles in J2ME:A specification layer above the configuration which describes the Java configuration for a
specific vertical market or device type.
Both J2ME configurations have one or more associated profiles, some of which may
themselves rely on other profiles.
Mobile Information Device Profile (MIDP)
PDA Profile (PDAP)
Foundation Profile
Personal Basis and Personal Profiles
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 4
RMI Profile
Game Profile
Application Development:MIDlets vs Applets:
Simple HelloMIDlet
Go to StartPrograms Sun Java (TM) Wireless Toolkit 2.5.2 for CLDC
Wireless Toolkit 2.5.2.
Click on the New Project button and name your project HelloProject and your
MIDlet HelloMidlet.
Once you press Create Project, Wireless tool kit will create a bunch of directories
for your project in the apps subdirectory. We're going to ignore most of them for
the moment and focus on a few important ones
C:\j2mewtk\apps\HelloProject - the main directory for your project
C:\j2mewtk\apps\HelloProject\bin - where Wireless tool kit stores .jar, .jar
and manifest.mf files
C:\j2mewtk\apps\HelloProject\classes - where the class files are stored
C:\j2mewtk\apps\HelloProject\src - where the source .java files are stored
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 5
Creating the Helloworld project:Step:-1 Click on Wireless Toolkit 2.5.2 under the group: All ProgramsSun Java(TM) Wireless
Toolkit 2.5.2 Wireless Toolkit 2.5.2
Step:-2 Click on 'New Project...' button.
Step:-3 Enter project name as 'Helloworld'. Enter MIDlet name as 'Helloworld'. Note that the
Midlet name is the same as the name of the class in the source code, which extends the
MIDlet class, otherwise your application wont run.
Step:-4 Another window pops up where you have to select a target platform. Select 'MIDP 1.0'
from the drop down list.
Page 6
Step:-5 After you click OK, the project is created and the Wireless Toolkit tells you the name of
the folder where you can create your source code files. The path of the source code
folder is displayed in the debug output window as shown below.
Page 7
Page 8
1. Write a j2me program to show how to change the font size and colour
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 9
Page 10
}
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.drawLine(0, f1.getHeight() + yPos - 1, width, f1.getHeight() + yPos - 1);
g.drawString("MEDIUM FONT", 0, yPos, Graphics.LEFT | Graphics.TOP);
g.setColor(BLACK);
//g.drawLine(0, f2.getHeight() + yPos - 1, width, f2.getHeight() + yPos - 1);
yPos = yPos + f1.getHeight() + 10;
g.setFont(f3);
g.drawString("SMALL FONT", 0, yPos, Graphics.LEFT | Graphics.TOP);
yPos = yPos + f1.getHeight() + 10;
g.drawLine(0, f3.getHeight() + yPos - 1, width, f3.getHeight() + yPos - 1);
painting = false;
}
}
}
OUTPUT:-
Page 11
Page 12
* paste
* delete
* select all
* unselect all
Class name: menucreation
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 command;
public StringItem st;
public menucreation()
{
display=Display.getDisplay(this);
ch=new ChoiceGroup("Edit",Choice.EXCLUSIVE);
ch.append("cut",null);
ch.append("copy",null);
ch.append("paste",null);
ch.append("delete",null);
ch.append("select all",null);
ch.append("unselect all",null);
ch.setSelectedIndex(1, true);
command=new Command("Select list item",Command.OK,1);
form=new Form("");
form.append(ch);
form.addCommand(command);
form.setCommandListener(this);
st=new StringItem("","");
}
public void startApp()
{
display.setCurrent(form);
}
public void pauseApp()
{
}
Page 13
Page 14
Page 15
ch1.setSelectedIndex(1, true);
form.append(ch1);
View=new Command("View",Command.OK,1);
Exit =new Command("Exit",Command.EXIT,1);
Back=new Command("Back",Command.BACK,1);
form.addCommand(View);
form.addCommand(Exit);
form1.addCommand(Back);
form.setCommandListener(this);
form1.setCommandListener(this);
form.setItemStateListener(this);
}
public void startApp()
{
display.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command command,Displayable displayable)
{
if(displayable==form)
{
if(command==View)
{
boolean opt[]=new boolean[ch.size()];
options=new StringItem("","");
String values="";
ch.getSelectedFlags(opt);
options.setText("");
for(int i=0;i<opt.length;i++)
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 16
{
if(opt[i])
{
values+=ch.getString(i)+"\n";
}
}
options.setText(values);
form1.append(options);
display.setCurrent(form1);
}
else if(command==Exit)
{
destroyApp(true);
notifyDestroyed();
}
}
else if(displayable==form1)
{
if(command==Back)
{
display.setCurrent(form);
options.setText("");
}
}
}
public void itemStateChanged(Item item)
{
if(item==ch1)
{
int i=0;
int size=ch.size();
while(i<0)
{
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 17
if(ch1.getSelectedIndex()==0)
ch.setSelectedIndex(i, true);
else
ch.setSelectedIndex(i, false);
i++;
}
}
}
}
OUTPUT:-
Page 18
Page 19
import javax.microedition.lcdui.*;
public class bargraph extends MIDlet implements CommandListener
{
public Form form;
public Command exitCommand;
public Command OkCommand;
public Command backCommand;
public Displayable d;
public Display display;
public TextField textfield1;
public TextField textfield2;
public TextField textfield3;
public TextField textfield4;
public TextField textfield5;
public bargraph()
{
display=Display.getDisplay(this);
form=new Form("bargraph");
textfield1=new TextField("Value1:-","",30,TextField.ANY);
textfield2=new TextField("Value2:-","",30,TextField.ANY);
textfield3=new TextField("Value3:-","",30,TextField.ANY);
textfield4=new TextField("Value4:-","",30,TextField.ANY);
textfield5=new TextField("Value5:-","",30,TextField.ANY);
form.append(textfield1);
form.append(textfield2);
form.append(textfield3);
form.append(textfield4);
form.append(textfield5);
OkCommand=new Command("Ok",Command.OK,1);
exitCommand=new Command("Exit",Command.EXIT,1);
backCommand=new Command("Back",Command.BACK,1);
form.addCommand(OkCommand);
form.addCommand(exitCommand);
form.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 20
}
public void commandAction(Command command,Displayable displayable)
{
if(displayable==form)
{
if(command==OkCommand)
{
int[] data=new int[5];
data[0]=Integer.parseInt(textfield1.getString());
data[1]=Integer.parseInt(textfield2.getString());
data[2]=Integer.parseInt(textfield3.getString());
data[3]=Integer.parseInt(textfield4.getString());
data[4]=Integer.parseInt(textfield5.getString());
d=new BarCanvas(data);
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)
{
g.setColor(255,255,255);
g.fillRect(0,0,this.getWidth(), this.getHeight());
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 21
5. Create a MIDP application which Examine, that a phone number, which a user entered
in given format.
Class name: inputchecking
Program:import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 22
Page 23
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)
st.setText("OK");
else
{
st.setText("wrong\n Phone Number Format is xxx xxx xxxx\nArea code must be 040|
050|041|0400|044");
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 24
}
form1.append(st);
}
}
}
OUTPUT:-
Page 25
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. Shows how to make a SOCKET connection
from the phone to port 80.
Class name: socket.java
Program:import javax.microedition.midlet.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class socket extends MIDlet
{
//StreamConnection allows bidirectional communication private StreamConnection
streamConnection = null;
//use OutputStream to send requests
private OutputStream outputStream = null;
private DataOutputStream dataOutputStream = null;
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 26
//use InputStream to receive responses from Web server private InputStream inputStream = null;
private DataInputStream dataInputStream = null;
//specify the connect string
private String connectString = "socket://www.java-samples.com:80";
//use a StrignBuffer to store the retrieved page contents private StringBuffer results;
//define GUI components
private Display myDisplay = null;
private Form resultScreen;
private StringItem resultField;
public socket()
{
// initializing GUI display results = new StringBuffer();
myDisplay = Display.getDisplay(this);
resultScreen = new Form("Page Content:");
}
public void startApp()
{
try
{
//establish a socket connection with remote server streamConnection = (StreamConnection)
Connector.open(connectString);
//create DataOuputStream on top of the socket connection outputStream =
streamConnection.openOutputStream();
dataOutputStream = new DataOutputStream(outputStream);
//send the HTTP request
dataOutputStream.writeChars("GET /index.htm HTTP/1.0 \n");
dataOutputStream.flush();
//create DataInputStream on top of the socket connection inputStream =
streamConnection.openInputStream();
dataInputStream = new DataInputStream(inputStream);
//retrieve the contents of the requested page from Web server int inputChar;
while ( (inputChar = dataInputStream.read()) != -1)
{
results.append((char) inputChar);
}
//display the page contents on the phone screen
resultField = new StringItem(null, results.toString());
resultScreen.append(resultField);
myDisplay.setCurrent(resultScreen);
}
catch (IOException e)
{
System.err.println("Exception caught:" + e);
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 27
}
finally
{
//free up I/O streams and close the socket connection
try
{
if (dataInputStream != null) dataInputStream.close();
}
catch (Exception ignored)
{
}
try
{
if (dataOutputStream != null) dataOutputStream.close();
}
catch (Exception ignored)
{
}
try
{
if (outputStream != null) outputStream.close();
}
catch (Exception ignored)
{
}
try
{
if (inputStream != null) inputStream.close();
}
catch (Exception ignored)
{
}
try
{
if (streamConnection != null) streamConnection.close();
}
catch (Exception ignored)
{
}
}
}
public void pauseApp()
{
}
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 28
OUTPUT:-
Page 29
7. 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.
Class name: Demo.java
Program:import java.io.*;
import java.util.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
public class Demo extends MIDlet implements CommandListener
{
private String username;
private String url = "http://localhost:8082/mobileDemo/indexDB.jsp";
private Display display;
private Command exit = new Command("EXIT", Command.EXIT, 1);
private Command login = new Command("Login", Command.SCREEN, 1);
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 30
Page 31
}
public class DBConn implements Runnable
{
Demo midlet;
private Display display;
String user;
String pwd;
public DBConn(Demo midlet)
{
this.midlet = midlet;
display = Display.getDisplay(midlet);
}
public void start()
{
Thread t = new Thread(this);
t.start();
}
public void run()
{
StringBuffer sb = new StringBuffer();
try
{
HttpConnection c = (HttpConnection) Connector.open(url);
c.setRequestProperty("User-Agent","Profile/MIDP-1.0,Configuration/CLDC-1.0");
c.setRequestProperty("Content-Language","en-US");
c.setRequestMethod(HttpConnection.POST);
DataOutputStream os = (DataOutputStream)c.openDataOutputStream();
os.writeUTF(user.trim());
os.writeUTF(pwd.trim());
os.flush();
os.close();
// Get the response from the page.
DataInputStream is =(DataInputStream)c.openDataInputStream();
//is = c.openInputStream();
int ch;
sb = new StringBuffer();
while ((ch = is.read()) != -1)
{
sb.append((char)ch);
}
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 32
showAlert(sb.toString());
is.close();
c.close();
}
catch (Exception e)
{
showAlert(e.getMessage());
}
}
/* This method takes input from user like db,user and pwd and pass to servlet */
public void connectDb(String user,String pwd)
{
this.user = user;
this.pwd = pwd;
}
/* Display Error On screen*/
private void showAlert(String err)
{
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
};
}
indexDB.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.ResultSet"%>
<%@ page import="java.sql.DriverManager"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.Statement"%>
<%@page import="javax.swing.JOptionPane" %>
<%
boolean found = false;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:hari","system","manager");
Statement statement = con.createStatement();
String name = request.getParameter("username");
String pwd = request.getParameter("password");
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 33
Output:
Page 34
8(a). Develop a simple Java ME project to retrieve student marks when regd.no is given.
Note: Use Apache Tomcat Server as Web Server and Mysql as Database Server.
Procedure:
Step1: Create a database table with the following commands. (Assume that 'mysql' database is
installed in 'c:\mysql' folder)
c:\>cd mysql
c:\mysql>cd bin
c:\mysql\bin>mysql
mysql> create database stud;z
Query OK, 1 row affected (0.04 sec)
mysql> use stud;
Database changed
mysql> create table student(sno varchar(10),name varchar(20),moad
integer(2),ws integer(2),spm integer(2),st integer(2),ds integer(2),mefa integer(2));
Query OK, 0 rows affected (0.01 sec)
mysql> insert into student values('10731a1227','venkat',66,77,88,66,77,88);
Query OK, 1 row affected (0.00 sec)
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 35
Page 36
Step 3: Create a Java ME program with the following code and deploy in either wireless toolkit
or netbeans IDE.
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import java.io.*;
public class StudentMidlet extends MIDlet implements CommandListener {
Display display;
Form form;
TextField tf;
String str;
String url= "http://localhost:7000/test4/login.jsp";
Command back= new Command("Back", Command.BACK, 0);
Command submit= new Command("Submit", Command.OK, 2);
Command exit= new Command("Exit", Command.STOP, 3);
private StudentMidlet.Test test;
public StudentMidlet()
{
}
public void startApp() throws MIDletStateChangeException
{
display = Display.getDisplay(this);
form = new Form("Student Information Retrieval");
tf = new TextField("Enter Student No:","",30,TextField.ANY );
form.append(tf);
form.addCommand(submit);
form.addCommand(exit);
form.setCommandListener(this);
display.setCurrent(form);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable d) {
if (c == exit) {
destroyApp(true);
notifyDestroyed();
}
else if (c == back) {
display.setCurrent(form);
}
else if (c == submit) {
str = tf.getString();
test = new StudentMidlet.Test(this);
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 37
test.start();
test.setString(str);
}
}
class Test implements Runnable {
StudentMidlet midlet;
private Display display;
String text;
public Test(StudentMidlet midlet) {
this.midlet = midlet;
display = Display.getDisplay(midlet);
}
public void start() {
Thread t = new Thread(this);
t.start();
}
public void run() {
StringBuffer sb = new StringBuffer();
try {
HttpConnection c = (HttpConnection) Connector.open(url);
c.setRequestProperty(
"User-Agent","Profile/MIDP-1.0, Configuration/CLDC-1.0");
c.setRequestProperty("Content-Language","en-US");
c.setRequestMethod(HttpConnection.POST);
DataOutputStream os =
(DataOutputStream)c.openDataOutputStream();
os.writeUTF(text.trim());
os.flush();
os.close();
// Get the response from the servlet page.
DataInputStream is =(DataInputStream)c.openDataInputStream();
//is = c.openInputStream();
int ch;
sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char)ch);
}
showAlert(sb.toString());
is.close();
c.close();
}
catch (Exception e) {
showAlert(e.getMessage());
}
}
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 38
/* This method takes input from user like text and pass to jsp */
public void setString(String text) {
this.text = text;
}
/* Display Output or Error On screen*/
private void showAlert(String str) {
Alert a = new Alert("");
a.setString(str);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
};
}
Step 4: The output is displayed on the mobile emulator as shown below on Student Information
will be displayed as shown in the following mobile emulator.
Page 39
Page 40
Page 41
----test5
|
|
-----WEB-INF
|
|--lib--mysql-connector-java-3.0.8-stable-bin.jar
|
----login.jsp
Note: You can download 'mysql-connnector-java-3.0.8-stable-bin.jar' from the link
'http://mirrors.ibiblio.org/maven2/mysql/mysql-connector-java/3.0.8/' Adding this jar file is
mandatory to make sure that this program is running
Step 3: Create a Java ME program with the following code and deploy in either wireless toolkit
or netbeans IDE.
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import java.io.*;
public class MoviesMidlet extends MIDlet implements CommandListener {
Display display;
Form form;
TextField tf;
String str;
String url= "http://localhost:7000/test5/login.jsp";
Command back= new Command("Back", Command.BACK, 0);
Command submit= new Command("Submit", Command.OK, 2);
Command exit= new Command("Exit", Command.STOP, 3);
private MoviesMidlet.Test test;
public MoviesMidlet() {}
public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
form = new Form("Movie Information Retrieval");
tf = new TextField("Enter Theatre Name","",30,TextField.ANY );
form.append(tf);
form.addCommand(submit
form.addCommand(exit);
form.setCommandListener(this);
display.setCurrent(form);
}
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 42
Page 43
DataOutputStream os =(DataOutputStream)c.openDataOutputStream();
os.writeUTF(text.trim());
os.flush();
os.close();
// Get the response from the jsp page.
DataInputStream is =(DataInputStream)c.openDataInputStream();
//is = c.openInputStream();
int ch;
sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char)ch);
}
showAlert(sb.toString());
is.close();
c.close();
}
catch (Exception e) {
showAlert(e.getMessage());
}
/* This method takes input from user like text and pass to jsp */
public void setString(String text) {
this.text = text;
}
/* Display Error On screen*/
private void showAlert(String str) {
Alert a = new Alert("");
a.setString(str);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
};
}
Step 4: The output is displayed on the mobile emulator as shown NEXT PAGE:
Page 44
Android Introduction:
The goal of this is to learn the fundamentals of developing Android Applications, from
project creation to installation on a physical device. More specifically you should gain the
knowledge of how to use basic development tools to support the application development
process, as well as the key components of an Android application itself.
1. Setting Up the Development Environment
1.1 Download/Install the SDK:
Go to http://developer.android.com/sdk/index.html.
Unpack to a convenient location - Remember the full path to this location, we will
refer to it as <android_sdk_dir
1.2 Windows:
1. Right-click My Computer.
2. Click Properties.
3. Click Advanced tab.
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 45
Before we can begin developing we must download and install this platform:
Select the menu Window "Android SDK and AVD Manager", or click on the black
phone shaped icon in the toolbar.
Expand the Google Android site in the "Site, Packages, and Archives" Tree.
Accept the Terms for all packages and click Install Accepted.
Page 46
Page 47
values: This folder will hold files that contain value type resources, such as string and
integer constants. It already contains a file called strings.xml. Double clicking on this
file will open up the Android Resource Editor. Notice that there are two strings in there
already, one of which is named 'app_name'. If you select this value, on the right hand
side of the editor you should see the Application Name you entered in the project
creation wizard. You can use this editor to add new resources to your application.
gen: This folder will contain Java files that get auto-generated by ADT. Notice that it
already contains one file called "R.java".
R.java: This is a special static class that is used for referencing the data contained in
your resource files. If you open this file you will see a number of static inner classes for
each of the resource types, as well as static constant integers within them. Notice that
the names of the member variables are the same as the names of the values in your
resource files. Each value in a resource file is associated with an integer ID, and that ID
is stored in a member variable of the same name, within a static class named after its
data type. The 'app_name' resource value has an ID and is of value type 'string'. The
ADT automatically adds an integer constant to the R.string class and names it
'app_name'.
assets: This folder is for asset files, which are quite similar to resources. The main
difference being that anything stored in the 'assets' folder has to be accessed in the
classic 'file' manipulation style. For instance, you would have to use the Asset Manager
class to open the file, read in a stream of bytes, and process the data. You will not be
using assets quite as extensively as you will be using resources.
AndroidManifest.xml: Every project has a file with this exact name in the root
directory. It contains all the information about the application that Android will need to
run it: Package name used to identify the application. List of Activities, Services,
Broadcast receivers, and Content Provider classes and all of their necessary information,
including permissions. System Permissions the application must define in order to make
use of various system resources, like GPS. Application defined permissions that other
applications must have in order to interact with this application. Application profiling
information. Libraries and API levels that the application will use.
default. Properties: This file contains all of the project settings, such as the build target
you chose in the project creation wizard. If you open the file, you should see 'target=4',
which is your build target. You should never edit this file manually. If you wish to edit
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 48
the project properties, do so by right-clicking the project in the 'Package Explorer' panel,
and selecting 'Properties'.
Page 49
9. Write an Android application program that displays Hello World using Terminal.
To create a simple Hello World Android project can be done either with Eclipse or Android
Studio. Here I am going to explain how it can be created by using Android Studio 0.8.0.
Android Studio:
Studio can be downloaded from the below link.
http://tools.android.com/download/studio/beta
Pre-requisite:
Ensure appropriate JDK version is installed.
Download appropriate Android SDK based on the version we are developing.
Page 50
Page 51
Page 52
Click on the finish button. The project gets created and will be shown as below
Files /
Components
Important
files and
directory of
Android
project to be
known and
their purpose
1. src
This
contains the .java source files for your project. By default, it includes an
Page 53
MainActivity.java source file having an activity class that runs when your app is launched
using the app icon.
2. generated - This contains the .R file, a compiler-generated file that references all the
resources found in your project. You should not modify this file
3. bin - This folder contains the Android package files .apk built by the ADT during the
build process and everything else needed to run an Android application.
4. res/drawable-hdpi - This is a directory for drawable objects that are designed for highdensity screens.
5. res/layout - This is a directory for files that define your app's user interface.
6. res/values - This is a directory for other various XML files that contain a collection of
resources, such as strings and colors definitions.
7. AndroidManifest.xml - This is the manifest file which describes the fundamental
characteristics of the app and defines each of its components.
String file:
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 54
The strings.xml file is located in the res/values folder and it contains all the text that your
application uses. For example, the names of buttons, labels, default text, and similar types of
strings go into this file. This file is responsible for their textual content. For example, a default
strings file will look like as following file.
R file:
The gen/myapps.helloworld/R.java file is the glue between the activity Java files like
Main.java and the resources like strings.xml. It is an automatically generated file and you should
not modify the content of the R.java file. Following is a sample of R.java file.
Layout File:
The activity_main.xml is a layout file available in res/layout directory, that is referenced
by your application when building its interface. You will modify this file very frequently to
change the layout of your application. For your "Hello World!" application, this file will have
following content related to default layout.
Page 55
Text Mode
Layout
Design
Running
app on
Emulator
Emulator
takes more
time to
load so before running app we should start emulator. Emulator can be started from SDK manager
tools Manage AVDs.
Page 56
AVD Manager
Create the AVD and click on the start to run the emulator
Page 57
10. Write an Android application program that displays Hello World using Eclipse.
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 58
Aim: To write an Android application program that displays Hello World using Eclipse.
Implementation:
Step1: Open Eclipse.
Step2: Click the menu File --> New Project.
Step3:
Expand the Android folder and select Android Project.
Page 59
Step4:
i)
Page 60
Step5:
The resources for an Android project are stored in the res folder of your project hierarchy, which
includes drawable, layout, and values subfolders. The ADT plug-in interprets these XML
resources to provide design time access to them through the R variable .
The following code snippet shows the UI layout defined in the main.xml file created by the
Android.
Page 61
Defining UI in XML and inflating it is the preferred way of implementing your user interfaces;
asset neatly decouples your application logic from your UI design.
The xml UI layout has been added to res\layout\main.xml.We can use the Android Layout Editor
to create xml layout, we can also code them manually. Lets take a look at this file:
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android: layout_height="wrap_content"
android: text="@string/hello" />
</LinearLayout>
//values/strings.xml//
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">HelloWorld</string>
<string name="hello">Hello World, HelloWorld! </string>
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 62
</resources>
HelloWorld.java
package com.cse.view;
import android.app.Activity;
import android.os.Bundle;
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Execution:
To execute application right-clickon the project in the Package Explorer, then select Run As
Android Application
Page 63
View the list of installed applications in the emulator and find the helloworld application
Page 64
11. Write an Android application program that accepts a name from the user and displays the
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 65
Step3:
Expand the Android folder and select Android Project.
Page 66
Step4:
i)
ii) You can change the location of where you would like to save the project by un-selecting
the Default Location" check box, and supplying your own location.
iii) Check "Android 2.2" from the Build Target
Fill in the Properties:
Application Name = stringdisplay.This is the friendly name of the application, thats hows up on
the device.
Package Name = com.cse.view. This is the namespace for the project, followsstandard Java
conventions.
Create Activity = stringdisplay. This optional field will automatically create a "MainActivity"
class for the project. You can think of the Main Activity as the Home Page for your application.
Min SDK Version = 8.
iv)Click finish.
Page 67
Step5:
The resources for an Android project are stored in the res folder of your project hierarchy, which
includes drawable, layout, and values subfolders. The ADT plug-in interprets these XML
resources to provide design time access to them through the R variable.
The following code snippet shows the UI layout defined in the main.xml file created by the
Android
Page 68
The xml UI layout has been added to res\layout\main.xml.We can use the Android Layout Editor
to create xml layout, We can also code them manually . Lets take a look at this file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<EditText
android:text=""
android:id="@+id/EditText01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
<Button android:text="send"
android:id="@+id/Button01"
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 69
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
Step6:
projects src/ directory contains the standard Java-style tree of directories based upon the Java
package you used when you created the project resulted in src/com/cse/view/. Inside the
innermost directory you should find a regenerated source file named stringdisplay.java, which is
where your first activity will go.
package com.cse.view;
import android.view.View;
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 70
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import android.os.Bundle;
public class stringdisplay extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn=(Button)findViewById(R.id.Button01);
final EditText et=(EditText)findViewById(R.id.EditText01);
btn.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
String s=et.getText().toString();
Toast.makeText(getApplicationContext(),"welcome to"+s,100).show();
}
});
}
}
Execution:
To execute application right-click on the project in the Package Explorer, then select Run As->
Android application
Page 71
View the list of installed applications in the emulator and find the stringdisplay application
Page 72
Page 73
(i) LinearLayout
(ii) RelativeLayout
(iii) TableLayout
(iv) GridView layout
(i) Aim: To Write an Android application program that demonstrates LinearLayout
Implementation:
Step1:Open Eclipse.
Step2:Click the menu File New Project.
Step3:
Expand the Android folder and select Android Project.
Page 74
Step4:
i) Name the project as week12_1
ii) You can change the location of where you would like to save the project by un-selecting
the "Default Location" check box, and supplying your own location.
iii) Check "Android 2.2" from the Build Target
iv) Fill in the Properties:
Application Name = linear layout. This is the friendly name of the application that shows
up on the device.
Package Name = com.cse.iew. This is the namespace for the project, follows standard
Java conventions.
Create Activity = lineralayout. This optional field will automatically create a
"MainActivity" class for the project. You can think of the Main Activity as the Home Page for
your application.
Min SDK Version = 8.
v) Click "Finish".
Page 75
Step5:
The resources for an Android project are stored in the res folder of your project hierarchy, which
includes drawable, layout, and values subfolders. The ADT plug-in interprets these XML
resources to provide design time access to them through the R variable.
The following code snippet shows the UI layout defined in the main.xml file created by the
Android
The xml UI layout has been added to res\layout\main.xml.We can use the Android Layout Editor
to create xml layout, We can also code them manually . Lets take a look at this file:
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 76
Page 77
innermost directory you should find a pregenerated source file named lineralayout.java, which is
where your first activity will go.
package com.cse.iew;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 78
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.RadioGroup;
public class LinearLayout extends Activity {
private static final int HORIZONTAL = 0;
private static final int VERTICAL = 0;
private RadioGroup gravity;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
RadioGroup orientation = (RadioGroup) findViewById(R.id.orientation);
orientation.setOnClickListener((OnClickListener) this);
gravity=(RadioGroup)findViewById(R.id.gravity);
gravity.setOnLongClickListener((OnLongClickListener) this);
}
@SuppressWarnings("null")
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioGroup orientation = null;
if(group==orientation) {
if(checkedId==R.id.horizontal) {
orientation.setOrientation(LinearLayout.HORIZONTAL);
}
else{
orientation.setOrientation(LinearLayout.VERTICAL);
}
}
else if (group==gravity) {
if(checkedId==R.id.left) {
gravity.setGravity(Gravity.LEFT);
}
else if (checkedId==R.id.center) {
gravity.setGravity(Gravity.CENTER_HORIZONTAL);
}
else if (checkedId==R.id.right) {
gravity.setGravity(Gravity.RIGHT);
}
}
}
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 79
}
Execution:
To execute application right-click on the project in the Package Explorer, then select Run
AsAndroid application
View the list of installed applications in the emulator and find the linerarlayout application
Page 80
If we toggle the left radio button, the bottom RadioGroup adjusts to match
If we toggle the Center radio button, the bottom RadioGroup adjusts to match.
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 81
If we toggle the Right radio button, the bottom RadioGroup adjusts to match
Page 82
Implementation:
Step1:Open Eclipse.
Step2:Click the menu File -> New -> Project.
Step3:
Expand the Android folder and select Android Project.
Page 83
Step4:
i) Name the project as Rel
ii)You can change the location of where you would like to save the project by un-selecting
the "Default Location" check box, and supplying your own location.
iii) Check "Android 2.2" from the Build Target
iv)Fill in the Properties:
Application Name =relativelayout .This is the friendly name of the application, that
shows up on the device.
Package Name = com.view.rl. This is the namespace for the project, follows standard
Java conventions.
Create Activity = Relative. This optional field will automatically create a "MainActivity"
class for the project. You can think of the Main Activity as the Home Page for your application.
Min SDK Version = 8.
v) Click "Finish".
Page 84
Step5:
The resources for an Android project are stored in the res folder of your project hierarchy, which
includes drawable, layout, and values subfolders. The ADT plug-in interprets these XML
resources to provide design time access to them through the R variable .
The following code snippet shows the UI layout defined in the main.xml file created by the
Android
Page 85
The xml UI layout has been added to res\layout\main.xml.We can use the Android Layout Editor
to create xml layout, we can also code them manually .Lets take a look at this file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Enter email address" />
<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"
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 86
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@id/inputEmail"
android:layout_marginRight="10px"
android:text="Login" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/btnLogin"
android:layout_toRightOf="@id/btnLogin"
android:text="Cancel" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Register" />
</RelativeLayout>
RelativeLayoutExampleActivity.java
package com.cse.view;
import android.app.Activity;
import android.os.Bundle;
public class RelativeLayoutExampleActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Execution:
To execute application right-click on the project in the Package Explorer, then select Run As->
Android
Page 87
View the list of installed applications in the emulator and find the relativelayout application
Page 88
(iii)Aim:To Write an Android application program that demonstrates Grid View Layout.
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 89
Implementation:
Step1:Open Eclipse.
Step2:Click the menu File -> New -> Project.
Step3:
Expand the Android folder and select Android Project.
Step4:
i) Name the project as gridview
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 90
ii) You can change the location of where you would like to save the project by un-selecting
the "Default Location" check box, and supplying your own location.
iii) Check "Android 2.2" from the Build Target
iv) Fill in the Properties:
Application Name =tab .This is the friendly name of the application, that shows up on the
device.
Package Name = com.view.layout. This is the namespace for the project, follows standard
Java conventions.
Create Activity = sim. This optional field will automatically create a "MainActivity" class
for the project. You can think of the Main Activity as the Home Page for your application.
Min SDK Version = 8.
vi)click finish
Step5:
Page 91
The resources for an Android project are stored in the res folder of your project hierarchy, which
includes drawable, layout, and values subfolders. The ADT plug-in interprets these XML
resources to provide design time access to them through the R variable .
The following code snippet shows the UI layout defined in the main.xml file created by the
Android
Defining UI in XML and inflating it is the preferred way of implementing your user interfaces,
asit neatly decouples your application logic from your UI design.
The xml UI layout has been added to res\layout\main.xml.We can use the Android Layout Editor
to create xml layout, We can also code them manually .
Lets take a look at this file:
Page 92
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1">
<TableRow>
<TextView
android:text="URL:" />
<EditText android:id="@+id/entry"
android:layout_span="3"/>
</TableRow>
<View
android:layout_height="2px"
android:background="#0000FF" />
<TableRow>
<Button android:id="@+id/cancel"
android:layout_column="2"
android:text="Cancel" />
<Button android:id="@+id/ok"
android:text="OK" />
</TableRow>
</TableLayout>
Execution:
Page 93
To execute application right-clickon the project in the Package Explorer, then select Run As->
Android Application
View the list of installed applications in the emulator and find the tabapplication
Open tabapplication.You could see an activity screen like the one shown in figure
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 94
(iv)Aim: To Write an Android application program that demonstrates Grid View Layout.
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 95
Implementation:
Step1: Open Eclipse.
Step2: Click the menu File -> New -> Project.
Step3:
Expand the Android folder and select Android Project.
Step4:
i) Name the project as gridview
ii)You can change the location of where you would like to save the project by un-selecting
the "Default Location" check box, and supplying your own location.
iii) Check "Android 2.2" from the Build Target List. This identifies that the project is being built
to be compatible with Android versions 2.2 and later. Its generally preferred that you choose the
lowest build number possible, so as to be compatible with the largest number of existing systems
in place. This build target can be changed any time later on through the Project Properties menu.
iv) Fill in the Properties:
Application Name =tab .This is the friendly name of the application, that shows up on the
device.
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 96
Package Name = com.view.layout. This is the namespace for the project, follows standard
Java conventions.
Create Activity = sim. This optional field will automatically create a "Main Activity"
class for the project. You can think of the Main Activity as the Home Page for your application.
Min SDK Version = 8.This specifies the minimum API Level on which your application
can run. By default this is set to the API Level of the Build Target Platform. As new API's are
added to newer Versions, their API levels increase as well. A Program that uses an API Level of
four wont be able to run on a platform that has a lower API Level.
v) Click "Finish".
Step5:
The resources for an Android project are stored in the res folder of your project hierarchy,
whichincludes drawable, layout, and values subfolders. The ADT plug-in interprets these XML
resourcesto provide design time access to them through the R variable .
The following code snippet shows the UI layout defined in the main.xml file created by the
Android
Defining UI in XML and inflating it is the preferred way of implementing your user interfaces,
asit neatly decouples your application logic from your UI design.
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 97
The xml UI layout has been added to res\layout\main.xml.We can use the Android Layout Editor
to create xml layout, We can also code them manually . Lets take a look at this file:
Main.xml
<?xmlversion="1.0"encoding="utf-8"?>
<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<GridView
android:id="@+id/GridView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="50px"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
>
</GridView>
</RelativeLayout>
HelloWorld.java
package com.view.basics;
import android.app.Activity;
import android.os.Bundle;
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 98
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
public class HelloWorld extends Activity {
GridView gridView;
static final String[] num=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"
};
protected static final String TextView = null;
Page 99
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View v, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), ((TextView)
v).getText(),Toast.LENGTH_SHORT).show();
}
});
}
}
OnItemClickListener.java
package com.view.basics;
public interface OnItemClickListener extends android.widget.AdapterView.OnItemClickListener
{
}
Execution:
To execute application right-clickon the project in the Package Explorer, then select Run As->
Android Application
You could see an activity screen like the one shown in figure:
Page 100
13. Write an Android application program that converts the temperature in Celsius to
Fahrenheit.
Aim: To write an Android application program that converts the temperature in Celsius to
Fahrenheit.
Implementation:
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 101
Step3:
Expand the Android folder and select Android Project.
Page 102
Step4:
i) Name the project as week13
ii) You can change the location of where you would like to save the project by un-selecting
the "Default Location" check box, and supplying your own location.
iii) Check "Android 2.2" from the Build Target List. This identifies that the project is being built
to be compatible with Android versions 2.2 and later. Its generally preferred that you choose the
lowest build number possible, so as to be compatible with the largest number of existing systems
in place. This build target can be changed any time later on through the Project Properties menu.
iv) Fill in the Properties:
Application Name = converter.This is the friendly name of the application, that shows up on the
device.
Package Name = com.view.cse. This is the namespace for the project, follows standard Java
conventions.
Create Activity = week13. This optional field will automatically create a "Main Activity" class
for the project. You can think of the Main Activity as the Home Page for your application.
Min SDK Version = 8.This specifies the minimum API Level on which your application can run.
By default this is set to the API Level of the Build Target Platform. As new API's are added to
newer Versions, their API levels increase as well. A Program that uses an API Level of four
wont be able to run on a platform that has a lower API Level.
v) Click "Finish".
Page 103
Step5:
The resources for an Android project are stored in the res folder of your project hierarchy, which
includes drawable, layout, and values subfolders. The ADT plug-in interprets these XML
resources to provide design time access to them through the R variable .
The following code snippet shows the UI layout defined in the main.xml file created by the
Android
Page 104
Defining UI in XML and inflating it is the preferred way of implementing your user interfaces,
as it neatly decouples your application logic from your UI design.
The xml UI layout has been added to res\layout\main.xml.We can use the Android Layout Editor
to create xml layout, we can also code them manually. Lets take a look at this file:
<? xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
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"
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 105
/>
<EditTextandroid:text="@+id/EditText01"
android:id="@+id/EditText01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
<Button android:text="@+id/Button01"
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
It uses LinearLayout as a layout container for a TextView that displays the Hello
Worldgreeting.A string resource containing the display text has been placed into the
res\values\strings.xml file. The value is named 'hello. The Edit Text widget, which is a subclass
of the TextView used for labels. The default text in this label is null. Button is an Androidsupplied widget. Because we want to reference this button from our Java code, we need to give it
an identifier via the android: id attribute.android: text indicates the initial text to be displayed on
the button face (in this case, the string is convert) android:layout_width and
android:layout_height tell Android to have the buttons width and height fill the parent, in this
case the entire screen.
Step6:
projects src/ directory contains the standard Java-style tree of directories based upon the Java
package you used when you created the project resulted in src/com/vignan/cse/. Inside the
innermost directory you should find a pre generated source file named week13.java, which
Page 106
activity is the base class for the visual, interactive components of your application; it is roughly
equivalent to a Form in traditional desktop development. The following snippet shows the
skeleton code for an Activity-based class.
package com.view.cse;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class week13extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 107
setContentView(R.layout.main);
Button btn=(Button)findViewById(R.id.Button01);
final EditText et=(EditText)findViewById(R.id.EditText01);
btn.setOnClickListener(newOnClickListener()
{
public void onClick(View v)
{
String s=et.getText().toString();
Float c=Float.parseFloat(s);
Double f=(c*1.8)+32;
Toast.makeText(getApplicationContext(),"TEMPERTURE IN CELSIUS IS "+f,1000).show(); }
});
}
}
This activity contain, rather than instantiating the Button onCreate() callback, can reference the
one from the XML layout. The content view to be a view created in Java code, we set it to
reference the XML layout (setContentView (R.layout.main)). The R.java source file will be
updated when we rebuild this project to include a reference to our layout file (stored as main.xml
in our projects res/layout directory).
To get hands on our Button instance, use the findViewById() call. Since we identified our button
as @+id/button, we can reference the buttons identifier as R.id.button. Now, with the Button
instance in hand, we can set the callback and set the label as temperature in Fahrenheit.
Execution: To execute application right-click on the project in the Package Explorer, then select
Run As-> AndroidApplication
Page 108
View the list of installed applications in the emulator and find the converter application
Open converter application.You could see an activity screen like the one shown in figure
Now, enter the temperature in Celsius in textbox.
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 109
Now,click on convert.
Page 110
Week14:
Aim:To Write an Android application program that demonstrates intent in mobile application
development.
Implementation:
Step1:Open Eclipse.
Step2:Click the menu File -> New -> Project.
Step3:
Expand the Android folder and select Android Project.
Page 111
Step4:
i)
ii) You can change the location of where you would like to save the project by un-selecting
the "Default Location" check box, and supplying your own location.
iii) Check "Android 2.2" from the Build Target List. This identifies that the project is being built
to be compatible with Android versions 2.2 and later. Its generally preferred that you choose the
lowest build number possible, so as to be compatible with the largest number of existing systems
in place. This build target can be changed any time later on through the Project Properties menu.
iv) Fill in the Properties:
Application Name = Intent. This is the friendly name of the application, that shows up on
the device.
Package Name = com.intent.cse. This is the namespace for the project, follows standard
Java conventions.
Create Activity = first. This optional field will automatically create a "MainActivity"
class for the project. You can think of the Main Activity as the Home Page for your application.
Min SDK Version = 8.This specifies the minimum API Level on which your application
can run. By default this is set to the API Level of the Build Target Platform. As new API's are
added to newer Versions, their API levels increase as well. A Program that uses an API Level of
four wont be able to run on a platform that has a lower API Level.
v)Click "Finish".
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 112
Step5:
The resources for an Android project are stored in the res folder of your project hierarchy,
whichincludes drawable, layout, and values subfolders. The ADT plug-in interprets these XML
resourcesto provide design time access to them through the R variable .
The following code snippet shows the UI layout defined in the main.xml file created by the
Android
Page 113
Defining UI in XML and inflating it is the preferred way of implementing your user
asset neatly decouples your application logic from your UI design.
interfaces;
The xml UI layout has been added to res\layout\main.xml.We can use the Android Layout Editor
to create xml layout, we can also code them manually. Lets take a look at this file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 114
Page 115
Activity is the base class for the visual, interactive components of your application; it is roughly
equivalent to a Form in traditional desktop development. The following snippet shows the
skeleton code for an Activity-based class.
package com.intent.cse;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class firstextends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button bt=(Button) findViewById(R.id.Button01);
bt.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent it=newIntent(Navigation.this,Second.class
startActivity(it);
}
});
}
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 116
}
This activity contain, rather than instantiating the Button onCreate () callback, can
reference the one from the XML layout. The content view to be a view created in Java code, we
set it to reference the XML layout (setContentView (R.layout.main)). The R.java source file will
be updated when we rebuild this project to include a reference to our layout file (stored as
main.xml in our projects res/layout directory).
To get hands on our Button instance, use the find ViewById() call. Since we identified our button
as @+id/button, we can reference the buttons identifier as R.id.button. Now, with the Button
instance, Intents encapsulate a request, made to Android, for some activity or other Intent
receiver to do something. Here the activity intend to launch is second.class.To call, startActivity
() with the Intentthis will cause Android to find the best-match activity and pass the Intent to it
for handling. Your activity will not be informed when the child activity is complete.
Step7:
The activity first.java intend to launch the activity second.java so, now second.java and
second.xml files need to be created as given below.
projects src/ directory contains the standard Java-style tree of directories based upon the Java
package you used when you created the project resulted in src/com/intent/cse/.Right click on the
package the select new->class.
Page 117
projects src/ directory contains the standard Java-style tree of directories based uponthe Java
package you used when you created the project resultedin src/com/intent/cse/. Inside the
innermost directory you should find a pregeneratedsource file named second.java, which is
where your first activity will go.
Page 118
Activity is the base class for the visual, interactive components of your application; it is roughly
equivalent to a Form in traditional desktop development. The following snippet shows the
skeleton code for an Activity-based class.
package com.intent.cse;
import android.app.Activity;
import android.os.Bundle;
public class second extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
}
}
Page 119
In this activity, the content view to be a view created in Java code, we set it to reference the
XML layout (setContentView (R.layout.second)). The R.java source file will be updated when
we rebuild this project to include a reference to our layout file (stored as second.xml in our
projects res/layout directory).
To create second.xml file right click on res then select new->other.
Expand the Android folder and select Android XML file and click on next.
Page 120
The resources for an Android project are stored in the res folder of your project hierarchy, which
includes draw able, layout, and values subfolders. The ADT plug-in interprets these XML
resources to provide design time access to them through the R variable .
The following code snippet shows the UI layout defined in the second.xml file created by the
Android
Page 121
The xml UI layout has been added to res\layout\second.xml.We can use the Android Layout
Editor to create xml layout, we can also code them manually. Lets take a look at this file:
<? xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/icon">
</LinearLayout>
This XML layout sets default icon available in android2.2 as background.
Step8:
The activity second.java would need to be named in your AndroidManifest.xml file.
Page 122
The following shows the code defined in the AndroidManifest.xml file created by the Android:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.viiew.iintent"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Navigation"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
MOBILE APPLICATION DEVELOPMENT LAB RECORD
Page 123
<activity android:name=".second"/>
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>
Execution:
To execute application right-click on the project in the Package Explorer, then select Run As->
Android Application
View the list of installed applications in the emulator and find the Intent application.
Page 124
Open Intent application.You could see an activity screen like the one shown in figure.
Now, on clicking the button next you could see an activity screen like the one shown in figure.
Page 125
Page 126