Download MC lab manual by kalyan

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Week - 1: Installation Java Wireless Toolk (J2ME)
1) If the Java Development K
(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
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 Toolk
(formerly called J2ME Wireless Toolk )
from:
http://java.sun.com/products/sjwtoolk /download.html.
3) Run the installer (for example, for Windows is: sun_java_wireless_toolk 2_5_2-windows.exe). The installer checks whether a compatible Java environment
has been pre-installed. If not, is necessary to uninstall old versions Java and
perform Step 1 again. Once after successful installation Java and the tool k compile
this program and run the following program in the toolk .
Steps to run this program in toolk :
1. Start -> All Programs -> Sun Java Tool K -> Wireless Tool K
2. Click New Project – Enter Project Name -> Enter Class Name -> Click on Create Project.
3. Choose appropriate API Selection and Configurations.
4. Place Java Source file in WTK2.1 / WTK2.2\apps\projectname\src
5. Build the Project.
6. Run the Project.
Printing Hello World program in J2ME
import javax.microedition.lcdui.*;
import javax.microedition.midlet. *;
public class HelloMidlet extends MIDlet {
public HelloMidlet() {
}
public void startApp() {
Form form = new Form( "First Program" );
form.append( "Hello World" );
Display.get isplay(this).setCurrent(form );
}
public void pauseApp() {
}
public void destroyApp( boolean unconditional ) {
}
Result:
Experiement 1.
Write a J2ME program to show how to change the font color and size.
Colors.java
package hello;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
class MyCanvas1 extends Canvas
{
Protected void paint(Graphics graphics)
{
graphics.setColor(255,0,0);
graphics.setFont(Font.getFont(Font.FACE_PROPORTIONAL,
Font.STYLE_UNDERLINED,Font.SIZE_MEDIUM));
graphics.drawString(“RED SMALL”,10,10,Graphics.LEFT|Graphics.BASELINE);
graphics.setColor(0,255,0);
graphics.setFont(Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_ITALIC,Font.SIZE_SMALL));
graphics.drawString(“GREEN MEDIUM”,10,30,Graphics.LEFT|Graphics.BASELINE);
graphics.setColor(0,0,255);
graphics.setFont(Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD,Font.SIZE_LARGE));
graphics.drawString(“BLUE LARGE”,10,50,Graphics.LEFT|Graphics.BASELINE);
}
}
public class Colors extends MIDlet{
private Display d;
private MyCanvas1 canvas;
public Colors()
{
D=Display.getDisplay(this);
Canvas= new MyCanvas1();
}
protected void startApp()
{
d.setCurrent(canvas);
}
protected void pauseApp()
{
}
Protected void destroyApp(Boolean unconditional)
{
}
}
OUTPUT:
2. Write a J2ME program which creates the following kind of menu
*
*
*
*
*
*
cut
copy
past
delete
select all
unselect all
source code: Menus.java
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 String emst;
public MenuCreation()
{
display=Display.getDisplay(this);
ch=new ChoiceGroup("Ed ",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.setSelected ndex(1, true);
command=new Command("Select list i em",C mmand.OK,1);
form=new Form("");
form.append(ch);
form.addCommand(command);
form.setCommandListener(this); st=new String em("","");
}
public void startApp() { display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean uncond ional) {
}
public void commandAction(Command command,Displayable displayable)
{
if(command==command)
{
st.setText("");
st.setText("your selected option is "+ch.getString(ch.getSelectedIndex())); form.append(st);
}
}
}
OUTPUT:
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
Source code:
Mevents.java
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class MenuEvents extends MIDlet implements CommandListener, emStateListener {
public ChoiceGroup ch;
public ChoiceGroup ch1;
public Form form;
public Form form1;
public Display display;
public Command View;
public Command x ;
public Command Back;
public String tem options;
public em em;
public MenuEvents()
{
display=Display.getDisplay(this);
form=new Form("");
form1=new Form("Selcted O tions 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, tru );
form.append(ch);
ch1=new ChoiceGroup("",Choice.EXCLUSIVE); ch1.append("select all",null);
ch1.append("unselect all",null); ch1.setSelectedIndex(1, true);
form.append(ch1);
View=new Command("View",Command.OK,1); Ex =new Command("Ex ",Command.EX ,1);
Back=new Command("Back",Command.BACK,1);
form.addCommand(View);
form.addCommand(Ex );
form1.addCommand(Back);
form.setCommandListener(this);
form1.setCommandListener(this);
form.set emStateListener(this);
}
public void startApp()
{
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean uncond ional) {
}
public void commandAction(Command command,Displayable displayable)
{
if(displayable==form)
{
if(command==View)
{
boolean opt[]=new boolean[ch.size()];
options=new String em("","");
String values="";
ch.getSelectedFlags(opt);
options.setText("");
for(int i=0;i<opt.length;i++)< p=""> </ .leng h;i++)<>
{
if(opt[i])
}
{
values+=ch.getString(i)+"\n";
}
options.setT xt(valu s);
form1.append(options);
display.setCurr nt(form1);
}
else if(command==Ex )
{
destroyApp(true);
notifyDestroyed();
}
}
else if(displayable==form1)
{
if(command==Back)
{
display.setCurrent(form);
options.setText("");
}
}
}
public void emStateChanged( em em)
{
if( em==ch1)
{
int i=0;
int size=ch.size(); while(i<size)< p=""> </size)<>
{
}
}
}
}
if(ch1.getSelectedIndex()==0)
ch.setSelectedIndex(i, true);
else
ch.setSelectedIndex(i, false);
i++;
Output
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.
Source code:
Bargraphs.java
package hello;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Bargraphs extends MIDlet implements CommandListener{
public Form form;
public Command OkCommand;
public Command backCommand;
public Display display;
public BarGraph bg;
public TextField textfield1;
public TextField textfield2;
public TextField textfield3;
public TextField textfield4;
public Bargraphs()
{
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);
backCommand=new Command(“back”,Command.BACK,1);
form.addCommand(OkCommand);
form.setCommandListener(this);
}
Public void startApp(){
display.setCurrent(form);
}
public void pauseApp(){
}
public void destroyApp(Boolean unconditional){
}
public void commandAction(Command command, Displayable displayable)
{
if(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());
bg=new BarGraph(data);
bg.addCommand(backCommand);
bg.setCommandListener(this);
display.setCurrent(bg);
}
}
class BarGraph extends Canvas{
int[] data;
public int x;
public int y;
public int h;
public BarGraph(int[] data)
{
this.data=data;
x=10;
}
public void paint(Graphics g){
g.setColor(255,255,255);
g.fillRect(0,0,this.getWidth(),this.getHeight());
g.setColor(255,125,100);
int i=0;
int z=Math.max(Math.max(data[0],data[1],Math.max(data[2],data[3]));
h=z+10;
while(i<data.length)
{
y=h-data[i];
String s=(“”+data[i]);
g.fillRect(x,y,25,data[i]);
g.drawString(s,x,h+20,Graphics.LEFT|Graphics.BASELINE);
x+=30;
i++;
}}}
}
OUTPUT
5. create a 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)
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class InputChecking extends MIDlet implements CommandListener {
public Form form;
public TextField textField;
public Command exit;
public Command ok;
public StringItem st;
public Display display;
public InputChecking()
{
display=Display.getDisplay(this);
form=new Form("Insert the Phone number");
exit=new Command("Exit",Command.EXIT,1);
ok=new Command("Ok",Command.OK,1);
st=new StringItem("Phone Number is ","");
textField=new TextField("Phone;","",30,TextField.ANY);
form.append(textField);
form.addCommand(ok);
form.addCommand(exit);
form.setCommandListener(this);
}
public void startApp() {
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command cmd,Displayable displayable)
{
if(cmd==exit)
{
destroyApp(false);
notifyDestroyed();
}
else if(cmd==ok)
{
String s=textField.getString();
s=s.replace(' ', '.');
int len=s.length();
int i=0;
int c=0;
String s1="";
while(i<len)
{
if(s.charAt(i)=='.')
{
if(c==0)
{
if(s1.equals("040") || s1.equals("041") || s1.equals("050") || s1.equals("0400") ||
s1.equals("044"))
{
c++;
s1="";
}
}
if(c==1)
{
if(s1.length()-1==3)
{
c++;
s1="";
}
}
}
s1=s1+s.charAt(i);
i++;
}
if(s1.length()-1==3 || s1.length()-1==4 || s1.length()-1==5)
c++;
if(c==3)
st.setText("OK");
else
{
st.setText("wrong\n Phone Number Format is xxx xxx xxxx\n
Area code must be 040|050|041|0400|044");
}
form.append(st);
} }}
OUTPUT
6.write a sample program to show how to make a SOCKET connection from J2ME phone. This
J2ME sample program shows how to make a SOCKET connection from a J2ME Phone many a
times there is a need to connect backend HTTP server from the J2ME Application. Show how to
make a SOCKET connection from the phone to port 80.
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import java.io.*;
public class SocketMIDlet extends MIDlet implements CommandListener {
private static final int DEFAULT_PORT = 5000;
private static final String SERVER = "Server";
private static final String CLIENT = "Client";
private static final String[] names = { SERVER, CLIENT };
private static Display display;
private Form f;
private ChoiceGroup cg;
private boolean isPaused;
private TextField portField;
private Server server;
private Client client;
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
private Command startCommand = new Command("Start", Command.ITEM, 1);
public SocketMIDlet() {
display = Display.getDisplay(this);
f = new Form("Socket Demo");
cg = new ChoiceGroup("Please select peer", Choice.EXCLUSIVE, names,
null);
f.append(cg);
portField = new TextField("Port number:", String.valueOf(DEFAULT_PORT),
6, TextField.NUMERIC);
f.append(portField);
f.addCommand(exitCommand);
f.addCommand(startCommand);
f.setCommandListener(this);
display.setCurrent(f);
}
public boolean isPaused() {
return isPaused;
}
public void startApp() {
isPaused = false;
}
public void pauseApp() {
isPaused = true;
}
public void destroyApp(boolean unconditional) {
if (server != null) {
server.stop();
}
if (client != null) {
client.stop();
}
}
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == startCommand) {
String name = cg.getString(cg.getSelectedIndex());
int port = Integer.parseInt(portField.getString());
if (name.equals(SERVER)) {
server = new Server(this, port);
server.start();
} else {
client = new Client(this, port);
client.start();
} } }}
class Client implements Runnable, CommandListener {
private SocketMIDlet parent;
private Display display;
private Form f;
private StringItem si;
private TextField tf;
private boolean stop;
private Command sendCommand = new Command("Send", Command.ITEM, 1);
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
InputStream is;
OutputStream os;
SocketConnection sc;
Sender sender;
private int port;
public Client(SocketMIDlet m, int p) {
parent = m;
port = p;
display = Display.getDisplay(parent);
f = new Form("Socket Client");
si = new StringItem("Status:", " ");
tf = new TextField("Send:", "", 30, TextField.ANY);
f.append(si);
f.append(tf);
f.addCommand(exitCommand);
f.addCommand(sendCommand);
f.setCommandListener(this);
display.setCurrent(f);
}
/**
* Start the client thread
*/
public void start() {
Thread t = new Thread(this);
t.start();
}
public void run() {
String portString = String.valueOf(port);
try {
sc = (SocketConnection) Connector.open("socket://localhost:"
+ portString);
si.setText("Connected to server on port "+portString);
is = sc.openInputStream();
os = sc.openOutputStream();
// Start the thread for sending messages - see Sender's main
// comment for explanation
sender = new Sender(os);
// Loop forever, receiving data
while (true) {
StringBuffer sb = new StringBuffer();
int c = 0;
while (((c = is.read()) != '\n') && (c != -1)) {
sb.append((char) c);
}
if (c == -1) {
break;
}
// Display message to user
si.setText("Message received - " + sb.toString());
}
stop();
si.setText("Connection closed");
f.removeCommand(sendCommand);
} catch (ConnectionNotFoundException cnfe) {
Alert a = new Alert("Client",
"Please run Server MIDlet first on port " + portString,
null, AlertType.ERROR);
a.setTimeout(Alert.FOREVER);
a.setCommandListener(this);
display.setCurrent(a);
} catch (IOException ioe) {
if (!stop) {
ioe.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void commandAction(Command c, Displayable s) {
if ((c == sendCommand) && !parent.isPaused()) {
sender.send(tf.getString());
}
if ((c == Alert.DISMISS_COMMAND) || (c == exitCommand)) {
parent.notifyDestroyed();
parent.destroyApp(true);
}
}
/**
* Close all open streams
*/
public void stop() {
try {
stop = true;
if (sender != null) {
sender.stop();
}
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (sc != null) {
sc.close();
}
} catch (IOException ioe) {
}
}
}
class Server implements Runnable, CommandListener {
private SocketMIDlet parent;
private Display display;
private Form f;
private StringItem si;
private TextField tf;
private boolean stop;
private Command sendCommand = new Command("Send", Command.ITEM, 1);
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
InputStream is;
OutputStream os;
SocketConnection sc;
ServerSocketConnection scn;
Sender sender;
private int port;
public Server(SocketMIDlet m, int p) {
parent = m;
port = p;
display = Display.getDisplay(parent);
f = new Form("Socket Server");
si = new StringItem("Status:", " ");
tf = new TextField("Send:", "", 30, TextField.ANY);
f.append(si);
f.append(tf);
f.addCommand(exitCommand);
f.setCommandListener(this);
display.setCurrent(f);
}
public void start() {
Thread t = new Thread(this);
t.start();
}
public void run() {
String portString = String.valueOf(port);
try {
si.setText("Waiting for connection on port "+portString);
scn = (ServerSocketConnection) Connector.open("socket://:"
+ portString);
// Wait for a connection.
sc = (SocketConnection) scn.acceptAndOpen();
si.setText("Connection accepted");
is = sc.openInputStream();
os = sc.openOutputStream();
sender = new Sender(os);
// Allow sending of messages only after Sender is created
f.addCommand(sendCommand);
while (true) {
StringBuffer sb = new StringBuffer();
int c = 0;
while (((c = is.read()) != '\n') && (c != -1)) {
sb.append((char) c);
}
if (c == -1) {
break;
}
si.setText("Message received - " + sb.toString());
}
stop();
si.setText("Connection is closed");
f.removeCommand(sendCommand);
} catch (IOException ioe) {
if (ioe.getMessage().equals("ServerSocket Open")) {
Alert a = new Alert("Server", "Port " + portString
+ " is already taken.", null, AlertType.ERROR);
a.setTimeout(Alert.FOREVER);
a.setCommandListener(this);
display.setCurrent(a);
} else {
if (!stop) {
ioe.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void commandAction(Command c, Displayable s) {
if ((c == sendCommand) && !parent.isPaused()) {
sender.send(tf.getString());
}
if ((c == Alert.DISMISS_COMMAND) || (c == exitCommand)) {
parent.notifyDestroyed();
parent.destroyApp(true);
}
}
/**
* Close all open streams
*/
public void stop() {
try {
stop = true;
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (sc != null) {
sc.close();
}
if (scn != null) {
scn.close();
}
} catch (IOException ioe) {
}
}
}
class Sender extends Thread {
private OutputStream os;
private String message;
public Sender(OutputStream os) {
this.os = os;
start();
}
public synchronized void send(String msg) {
message = msg;
notify();
}
public synchronized void run() {
while (true) {
// If no client to deal, wait until one connects
if (message == null) {
try {
wait();
} catch (InterruptedException e) {
}
}
if (message == null) {
break;
}
try {
os.write(message.getBytes());
os.write("\r\n".getBytes());
} catch (IOException ioe) {
ioe.printStackTrace();
}
// Completed client handling, return handler to pool and
// mark for wait
message = null;
}
}
public synchronized void stop() {
message = null;
notify();
}
}
Output
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.
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.
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 login;
Query OK, 1 row affected (0.04 sec)
mysql> use login;
Database changed
mysql> create table users(user_id varchar(30),password varchar(30));
Query OK, 0 rows affected (0.01 sec)
mysql> insert into users values('dayakar','reddy');
Query OK, 1 row affected (0.00 sec)
Step 2: Create a 'jsp' file with the following code
<%@ page import ="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
<%@ page import ="java.io.*" %>
<%
DataInputStream in = new DataInputStream((InputStream)request.getInputStream());
String text=in.readUTF();
int index=0;
int end=text.length();
for(int i=0;i<end;i++)
{
if(text.charAt(i)=='$')
index=i;
}
String name=text.substring(0,index);
String pass=text.substring(index+1,end);
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/login","dayakar","");
Statement st= con.createStatement();
ResultSet rs=st.executeQuery("select * from users where user_id='"+name+"'");
if(rs.next())
{
String message;
if(rs.getString(2).equals(pass))
{
message = "Login Success"+"\n"+"welcome "+rs.getString(1);
}
else
{
message = "Login Failure: Please Try Again";
}
out.println(message);
}
%>
Install Tomcat Server 6.0 and deploy this 'jsp' program in the following directory structure
webapps
|
|
----Test
|
|
-----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 LoginAuthentication extends MIDlet implements CommandListener {
Display display = null;
Form form = null;
TextField tf1 = null;
TextField tf2=null;
String str = null;
String url = "http://localhost:7000/Test/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 Test test;
public LoginAuthentication() {}
public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
form = new Form("Request Servlet");
tf1 = new TextField("Enter Username:","",30,TextField.ANY );
tf2=new TextField("Enter Password:","",20,TextField.ANY|TextField.PASSWORD);
form.append(tf1);
form.append(tf2);
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 = tf1.getString()+"$"+tf2.getString();
test = new Test(this);
test.start();
test.getServlet(str);
}
}
class Test implements Runnable {
LoginAuthentication midlet;
private Display display;
String text;
public Test(LoginAuthentication 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 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 getServlet(String text) {
this.text = text;
}
/* Display Output or Error On screen*/
private void showAlert(String err) {
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
}
}
Step 4: The output is displayed on the mobile emulator as shown below
The following mobile emulator asks input for username and password
9. Write an Android application program that displays Hello World using Terminal.
In Eclipse, File > New > Android Application project, fill the fields as shown below and then
click next. Make sure that the minimum selected SDK version is equal or higher than the AVD
API version.
Select the BlankActivity and click next button.
Don’t change the default value and click next.
You will notice that ADT plugin has created the following directory structure. src folder contains
the source code, where as res folder contains the resources of the application which include
layout file, icons, menu, value etc. Also, there is an AndroidManifest file which defines the
property of the application(a kind of configuration file).
Now click the run on eclipse toolbar.
If the current project is launched for the first time, then eclipse shows the Run As dialog box as
given below. Select Android application from the list and click OK.
This will launch the AVD if it has not already been launched and will show the Activity
window.
On pressing the home button, you can see the application icon as shown below and once the icon
is clicked, the application gets launched and shows the following screen.
10. write an android application program that displays Hello World using Eclipse.
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">AndroidHello</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
</resources>
activity_hello.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HelloActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
</RelativeLayout>
HelloActivity.java
package com.srccodes.android;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class HelloActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello);
}
@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_hello, menu);
return true;
}
}
OUTPUT
11. write an Android application program that accepts a name from the user and displays the
hello name to the user in response as output using Eclipse.
Source Code:
Activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="@string/empty"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#A4C639" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="23dp"
android:text="@string/input_lable"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#0099FF" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView2"
android:layout_toRightOf="@+id/textView2"
android:background="#CCCCCC"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView2"
android:layout_marginTop="20dp"
android:background="#0099FF"
android:text="@string/sub"
android:textColor="#FFFFFF" />
</RelativeLayout>
FrmActivity.java
package com.javapapers.android.form;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class FrmActivity extends Activity {
Button mButton;
EditText mEdit;
TextView mText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frm);
mButton = (Button)findViewById(R.id.button1);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mEdit = (EditText)findViewById(R.id.editText1);
mText = (TextView)findViewById(R.id.textView1);
mText.setText("Welcome "+mEdit.getText().toString()+"!");
}
});
}
}
OUTPUT
12.write an Android application program that demonstrates the following
i) Linear Layout
ii) Relative Layout
iii) Table Layout
iv) Grid View Layout
i)Linear Layout
<?xml version="1.0" encoding="utf-8"?>
<!-- Parent linear layout with vertical orientation -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content"
android:text="Email:" android:padding="5dip"/>
<EditText android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_marginBottom="10dip"/>
<Button android:layout_width="fill_parent" android:layout_height="wrap_content"
android:text="Login"/>
<!-- Child linear layout with horizontal orientation -->
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" android:background="#2a2a2a"
android:layout_marginTop="25dip">
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content"
android:text="Home" android:padding="15dip" android:layout_weight="1"
android:gravity="center"/>
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content"
android:text="About" android:padding="15dip" android:layout_weight="1"
android:gravity="center"/>
</LinearLayout>
</LinearLayout>
package com.example.androidlayouts;
import android.app.Activity;
import android.os.Bundle;
public class AndroidLayoutsActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.linear_layout);
}
}
OUTPUT
ii) Relative Layout
<?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="Email" />
<EditText android:id="@+id/inputEmail" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_below="@id/label" />
<Button android:id="@+id/btnLogin" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_below="@id/inputEmail"
android:layout_alignParentLeft="true" android:layout_marginRight="10px"
android:text="Login" />
<Button android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_toRightOf="@id/btnLogin"
android:layout_alignTop="@id/btnLogin" android:text="Cancel" />
<Button android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_alignParentBottom="true" android:text="Register new Account"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
Output
iii) Table Layout
<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">
<!-- Row 1 with single column -->
<TableRow
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center_horizontal">
<TextView
android:layout_width="match_parent" android:layout_height="wrap_content"
android:textSize="18dp" android:text="Row 1" android:layout_span="3"
android:padding="18dip" android:background="#b0b0b0"
android:textColor="#000"/>
</TableRow>
<!-- Row 2 with 3 columns -->
<TableRow
android:id="@+id/tableRow1"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:id="@+id/TextView04" android:text="Row 2 column 1"
android:layout_weight="1" android:background="#dcdcdc"
android:textColor="#000000"
android:padding="20dip" android:gravity="center"/>
<TextView
android:id="@+id/TextView04" android:text="Row 2 column 2"
android:layout_weight="1" android:background="#d3d3d3"
android:textColor="#000000"
android:padding="20dip" android:gravity="center"/>
<TextView
android:id="@+id/TextView04" android:text="Row 2 column 3"
android:layout_weight="1" android:background="#cac9c9"
android:textColor="#000000"
android:padding="20dip" android:gravity="center"/>
</TableRow>
<!-- Row 3 with 2 columns -->
<TableRow
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center_horizontal">
<TextView
android:id="@+id/TextView04" android:text="Row 3 column 1"
android:layout_weight="1" android:background="#b0b0b0"
android:textColor="#000000"
android:padding="20dip" android:gravity="center"/>
<TextView
android:id="@+id/TextView04" android:text="Row 3 column 2"
android:layout_weight="1" android:background="#a09f9f"
android:textColor="#000000"
android:padding="20dip" android:gravity="center"/>
</TableRow>
</TableLayout>
OUTPUT
iv) Grid View Layout
AndroidGridLayoutActivity.java
package com.example.androidhive;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
public class AndroidGridLayoutActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
GridView gridView = (GridView) findViewById(R.id.grid_view);
// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter(this));
}
}
ImageAdapter.java
package com.example.androidhive;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.pic_1, R.drawable.pic_2,
R.drawable.pic_3, R.drawable.pic_4,
R.drawable.pic_5, R.drawable.pic_6,
R.drawable.pic_7, R.drawable.pic_8,
R.drawable.pic_9, R.drawable.pic_10,
R.drawable.pic_11, R.drawable.pic_12,
R.drawable.pic_13, R.drawable.pic_14,
R.drawable.pic_15
};
// Constructor
public ImageAdapter(Context c){
mContext = c;
}
@Override
public int getCount() {
return mThumbIds.length;
}
@Override
public Object getItem(int position) {
return mThumbIds[position];
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}}
OUTPUT
Related documents