Download File - KIET

Document related concepts
no text concepts found
Transcript
J2ME applications using Wireless Tool Kit
Click on the .exe file of sun java wireless toolkit and after specify the path to install (
for us we install at C:\WTK2.5.2_01) and accept to have a shortcut on your desktop,
the installation will begin and you will see a window like the one below.
Sun java wireless toolkit installation
To start, launch the java wireless toolkit from your desktop, then it window
will appear like this:
Click on the new project button beside the menu like below
how to create a new project
A windows will appear, type the project name and the Midlet className, like in
the window below, we choose
project name: HelloworldProject
Midlet class name: Helloworldmidlet
project in creation
Then another window called API selected will be show , for this project we
have nothing to change there , just make sure that you the profil that is selected there,
offer the most higher version of Midlet as Profile, and the CLDC as configuration,
for this tutorials , we choose the MSA as target profiles that give us Midlet 2.1 as
profile and the CLDC1.1 as configuration.
choice of MIDP profile and CLDC Configuration
Then click on ok to validate and you would get this message in the sun java wireless toolkit
window:
project-created
The message in the windows above, said that the project have been successfully
created and the folder bin, lib, res, src have been created in the appropriate folder of
the project and the project is already open at this time. Here is a small description of
those folders:
-Bin folder: Will content the executable file for your application(. Jar, .jad,
Manifest) for a real deployment, but at this stade it content a .jad file and a
MANIFEST only,
-Lib folder: Will be where we would specify any extern library that we will use
in our mobile application. It may be for ex: KXML librairy,…..
-Src folder: Will be where the source file will be store.
-Res folder: Will content files like pictures that we want to include or use in our
mobile application.
b-Create the source code file
Now open your textpad editor. Create a new file and start typing the content of
your java file in. Because your class will inherit from a Midlet class, you must prior
import the library that content the definition of the Midlet like this .
import javax.microedition.midlet.*;
Then you must declare your java class like this:
public class HelloWorldmidlet extends MIDlet {
public void startApp() { }
public void pauseApp() { }
public void destroyApp(boolean unconditional) {
} }
-HelloWorldmidlet : It is the class name and it is a public class,
-And it overrides 3 abstract methods :



startApp() which is the starter procedure of the application; it is the first
function to be executed, after that the HelloWorldmidelet instance has been
created;
pauseApp() – This procedure is executed at the occurrence of an event that
involves blocking the MIDlet application; for example if your mobile device is
launching this midlet and your same mobile device receives a phone call during
the execution of the application; this function will be excecute putting the
midlet in a break status.
destroyApp() – This procedure is used to close the application; it is executed at
the end of the application and contains routines used to release resources; it acts
like a destructor function;
All those 3 procedures are the minimal procedures that a midlet class should have,
but at this step of the source code the Helloworldmidlet has no any visual effects
because, no source code is implemented in their procedures so.
Now save the java file that is in your textpad editor in the src directory situated in
the project directory that has been created when you created your helloworldproject
from the Wireless tool kit, The way to reach this src folder look like this:
~ \j2mewtk\2.5.2\apps\HelloworldProject
save this file with the same name like your class name,do it like in this screen-shot
below:
save-java-file
Because we want our Helloworldmidlet to be able to show a hello world
message, the application must have access to the graphics resources controller’s. This
is done by defining a Display object which is initialized at the start of the application.
like this:
public class HelloWorldmidlet extends MIDlet
{
//reference to the application display manager
Display display;
public void startApp( )
{
display = Display.getDisplay(this);
}
public void pauseApp( ) { }
public void destroyApp(boolean unconditional) { }
}
Contrary to a java application on a computer, a java application on a mobile device
has a restriction to be display within a single form or window at a time , and also the
screen of mobile devices are smalls, so the Display reference is used to manage the
visual ressource and to say what form is active at a time.
So to display our hello world message, we need a form and a container for the
string, the library which containts class and methods to manage user interface is
javax.microedition.lcdui
-We must import it first like this: import javax.microedition.lcdui.*;
-We must declare the text box that we will use to show the hello world message:
private TextBox tb;
-We must implemente the constructor of our class, by instantiating the new textbox
with his message
public MidletHelloWorld( )
{
tb = new TextBox("My First MIDlet","Hello World !",100,0);
}
-We must activate the display with our text box in , whithin our startApp( )
procedure like below.
public void startApp( ){
display=Display.getDisplay(this);
display.setCurrent(tb);
}
Now our entire Helloworldmidlet java file will be like below:
import javax.microedition.lcdui.*;import javax.microedition.midlet.*;public class
Helloworldmidlet extendsMIDlet{Display display;PrivateTextBox tb;public
Helloworldmidlet(){
tb = new TextBox(“My First MIDlet”,”Hello World !”,100,0);
}
public void startApp()
{
display=Display.getDisplay(this);
display.setCurrent(tb);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
Now we are going to test our First mobile application that show helloworld.
Launch the wireless toolkit emulator, then open your project by hitting the open
project button and go through the folders where your project have been saved , then
select your project name and hit openproject button like below:
open the java2me project
You would get a screen like the screen-hot below:
project opened
c- Packaging
To compile and preverify the project we must go to project menu , then take package
then create package, like below:
packaging the application
This
would:
-First compile the java source file into a byte code file by creating a Helloworldmidlet.class
file
-Then would preverify the code before running it, the aim of the preverification is to check
any error in the source code, if the preverification run good, the packaging is done by:

o
o
o
Creating a file call MANIFEST.mf containing information like Midlet
name, Midlet version,Midlet vendor.
Creating a JAR file, for our case it would be helloworldmidlet.jar
that is the package containing the class and the MANIFEST file.
Creating a JAD file, for us it is Helloworldmidlet.jad this is the file that
allow to install the application on the mobile device.
If the packaging works well you would get a window like this :
compilation and preverification made with success
If not, It means that your java file has error and it would indicate the number of the
line where the error is. If everything work well then we can run our application in the
emulator;
Go to project click on run. The emulator will open, at this time the application is
not yet being executed, it shows a window with the name of your project like below:
mobile emulator launch
To start the application , you must select the Launch button (bottom right of the
emulator) to run your mobile application Then you would get on your mobile
emulator screen. a Hello World message like below:
j2me application is running showing hello world message
We have done with our Hello world mobile application using J2ME.
J2me application development using Eclipse:
To test a mobile application in a real environment, your personal mobile phone, the
MIDlet application must be installed on your mobile device.
STEP 1
To Create New J2ME Project
File -> New -> select j2me --> j2me Midlet suite -> click Next
Give the project name as HelloworldMobileApp and click Next
In Midlet Suite Properties use the default settings.
Click Next and Finish.
Now you can see it create your project in Project area.
STEP 2
Now select the project right click it and New --> Other
Select J2ME Midlet and click Next. Give a name for the midlet. In here i gave it as HelloworldMidlet and click finish.
It create the HelloworldMidlet class and inherit the some methods.
Now add these following code.
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class HelloworldMidlet extends MIDlet {
private Form form;
private Display display;
public HelloworldMidlet() {
form = new Form("My First J2ME App");
String msg = "Hello World";
form.append(msg);
display = Display.getDisplay(this);
display.setCurrent(form);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
notifyDestroyed();
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
}
STEP 3
We did finish coding now. But in order to run your app you have to do some configuration.
Right click the project --> Run as --> Run Configuration
Click Browse and select the project.
and Click Run
Now you can see it start the mobile device and show hello world.
Installation of Java Wireless Toolkit (J2ME)
1) If the Java Development Kit (JDK) is not there or only having the Java Runtime
Environment
(JRE)
installed,
install
the
latest
JDK
from
http://java.sun.com/javase/downloads/index.jsp.
Current stable release of Java is JDK 6 Update 7 but check the web page in case there are
newer non-beta releases available.
2) Next, download the Java Wireless Toolkit (formerly called J2ME Wireless Toolkit) from:
http://java.sun.com/products/sjwtoolkit/download.html.
3) Run the installer (for example, for Windows it is: sun_java_wireless_toolkit- 2_5_2windows.exe). The installer checks whether a compatible Java environment has been preinstalled. If not, it is necessary to uninstall old versions of Java and perform Step 1 again.
Once after successful installation of Java and the tool kit compile this program and run the
following program in the toolkit.
Steps to run this program in toolkit:
1. Start -> All Programs -> Sun Java Tool Kit -> Wireless Tool Kit
2. Click New Project – Enter Project Name -> Enter Class Name -> Click on Create Project.
3. Choose appropriate API Selection and Configurations.
4. Place Java Source file in WTK2.1 / WTK2.2
5. Build the Project.
6. Run the Project.
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class HelloWorld extends MIDlet{ private Form form;
private Display display;
public HelloWorld()
{
super();
}
public void startApp()
{
form = new Form("Hello World");
String msg = "Hello World!!!!!!!";
form.append(msg);
display = Display.getDisplay(this);
display.setCurrent(form);
}
public void pauseApp(){}
public void destroyApp(boolean unconditional)
{
notifyDestroyed();
}
}
Printing Hello World program in J2ME
Step-1:-Start ->AllPrograms->Sun Java Tool Kit->Wireless Tool Kit
Step-2:-Click New Project –Enter project Name as FirstMidlet -> Enter ClassName as
HelloMidlet->click on Create Project
Step-3:- A setting window will open up. Accept the defaults by clicking ok in that window.
Step-4:-Write Following Code in Notepad and save it as HelloMidlet.java
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class HelloMidlet extends MIDlet {
JBIET
public HelloMidlet() {
}
public void startApp() {
Form form = new Form( "First Program" );
form.append( "Hello World" );
Display.getDisplay(this).setCurrent( form );
}
Dept
public void pauseApp() {
}
public void destroyApp( boolean unconditional ) {
}
}
Step-5:-Place HelloMidlet.java in C:and
settingsmewtk.5.2
Step-6 :In the ktoolbar main window click on the “Build” button. When the build compiles
successfully then click on the “Run” button.
Week - 2 Create a program which creates to following kind of menu.
* cut
Dept
* copy
* past
* delete
* select all
* unselect al
Create a program which creates a select menu
Aim: Develop a MIDlet Application for select list item
Source code:
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() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command command,Displayable displayable)
{
if(command==command)
{
st.setText("");
st.setText("your
form.append(st);
}
}
}
Output:
Week 3:
selected
option
is
"+ch.getString(ch.getSelectedIndex()));
Create a program which creates a select menu for Eventhandling
Event Handling.
Create a menu which has the following options:
* 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 options off
Source code:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class MenuEvents extends MIDlet implements CommandListener,ItemStateListener {
public ChoiceGroup ch;
public ChoiceGroup ch1;
public Form form;
public
public
public
public
public
public
Form form1;
Display display;
Command View;
Command Exit;
Command Back;
StringItem options;
public Item item;
public MenuEvents()
{
display=Display.getDisplay(this);
form=new Form("");
form1=new Form("Selcted Options are");
ch=new ChoiceGroup("Preferences",Choice.MULTIPLE);
ch.append("cut",null);
ch.append("copy",null);
ch.append("paste",null);
ch.append("delete",null);
ch.setSelectedIndex(1, true);
form.append(ch);
ch1=new ChoiceGroup("",Choice.EXCLUSIVE);
ch1.append("select all",null);
ch1.append("unselect all",null);
ch1.setSelectedIndex(1, true);
form.append(ch1);
View=new Command("View",Command.OK,1);
Exit =new Command("Exit",Command.EXIT,1);
Back=new Command("Back",Command.BACK,1);
form.addCommand(View);
form.addCommand(Exit);
form1.addCommand(Back);
form.setCommandListener(this);
form1.setCommandListener(this);
form.setItemStateListener(this);
}
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++)< p=""> </opt.length;i++)<>
{
if(opt[i])
{
values+=ch.getString(i)+"";
}
}
options.setText(values);
form1.append(options);
display.setCurrent(form1);
}
else if(command==Exit)
{
destroyApp(true);
notifyDestroyed();
}
}
else if(displayable==form1)
{
if(command==Back)
{
display.setCurrent(form);
options.setText("");
}
}
}
public void itemStateChanged(Item item)
{
if(item==ch1)
{
int i=0;
int size=ch.size();
while(i<size)< p=""> </size)<>
{
if(ch1.getSelectedIndex()==0)
ch.setSelectedIndex(i, true);
else
ch.setSelectedIndex(i, false);
i++;
}
}
}
}
Output:
Week 4a:
Create a MIDP application,which draws a bargraph to display.Data values can be
given at int[]array?
Source Code:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class BarGraph extends MIDlet implements CommandListener{
public
public
public
public
public
public
Form form;
Command exitCommand;
Command OkCommand;
Command backCommand;
Displayable d;
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) {
}
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());
g.setColor(255, 125, 100);
int i=0;
y1=data[0];
h=200;
while(i<data.length)</data.length)
{
y=data[i];
h=200+y1-y;
g.fillRect(x, y,25 , h);
x+=30;
i++;
}
}
}
Output:
Week 4b
Create a MIDP Application,which draws a Pie 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:
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;
public class PieChart extends MIDlet implements CommandListener {
public Form form;
public Command exitCommand;
public Command OkCommand;
public Display display;
public TextField textfield1;
public TextField textfield2;
public TextField textfield3; Dept
public TextField textfield4;
public TextField textfield5;
public Displayable d;
public void startApp() {
display = Display.getDisplay(this);
form=new Form("Draw Pie");
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);
exitCommand = new Command("exit", Command.EXIT, 1);
OkCommand=new Command("Ok",Command.OK,1);
form.addCommand(OkCommand);
form.addCommand(exitCommand);
form.setCommandListener(this);
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable s) {
if(s==form)
{
if(c==exitCommand)
notifyDestroyed();
else if(c==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 PieChartCanvas(data);
d.addCommand(exitCommand);
d.setCommandListener(this);
display.setCurrent(d);
}
}
else if(s==d)
{
if(c==exitCommand)
display.setCurrent(form);
}
}
}
class PieChartCanvas extends Canvas {
int[] data;
int colors[] = { 0xFF0000, 0xA9E969, 0x00FFFF, 0xC675EC, 0x008800, 0x00C400 };
public PieChartCanvas(int[] data) {
this.data = data;
}
public void paint(Graphics g) {
int width = this.getWidth();
int height = this.getHeight();
g.setColor(255, 255, 255);
g.fillRect(0, 0, width, height);
int sum = 0;
for (int i = 0; i < data.length; i++) {
sum += data[i];
}
int deltaAngle = 360 * 100 / sum / 100;
int x = 4;
int y = 4;
int diameter;
if (width > height)
diameter = height - y * 2;
else
diameter = width - x * 2;
int startAngle = 0;
for (int i = 0; i < data.length; i++) {
g.setColor(colors[i]);
g.fillArc(x, y, diameter, diameter, startAngle, deltaAngle * data[i]);
startAngle += deltaAngle * data[i];
}
}
}
Output:
Week 5 :Input checking
Create a MIDP application which Examine ,that a phone number,which a user entered in given format.
*Area code should be one of the following :040,041,050,0400,044
Source Code:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class InputChecking extends MIDlet implements CommandListener {
public Form form1;
public TextField textfield1;
public Command exitCommand;
public Command okCommand;
public StringItem st;
public Display display;
public InputChecking()
{
display=Display.getDisplay(this);
form1=new Form("Insert the Phone number");
exitCommand=new Command("Exit",Command.EXIT,1);
okCommand=new Command("Ok",Command.OK,1);
st=new StringItem("Phone Number is ","");
textfield1=new TextField("Phone;","",30,TextField.ANY);
form1.append(textfield1);
form1.addCommand(okCommand);
form1.addCommand(exitCommand);
form1.setCommandListener(this);
}
public void startApp() {
display.setCurrent(form1);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command cmd,Displayable displayable)
{
if(cmd==exitCommand)
notifyDestroyed();
else if(cmd==okCommand)
{
String s=textfield1.getString();
s=s.replace(' ', '.');
int len=s.length();
int i=0;
int c=0;
String s1="";
while(i<LEN)< p=""> </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");
}
form1.append(st);
}
}
}
Output:
Week 6:
Creating a Simple Client-Server Application
Create, compile and run a basic UDP-based client-server application.
Creating the Datagram Server project
1) Click on Wireless Toolkit 2.5.2 under the group: All Programs→Sun Java
(TM) Wireless Toolkit 2.5.2.
2) Click on 'New Project...' button.
3) Enter project name as 'DatagramServer'. Enter MIDlet name as 'DatagramServer'.
Note that the Midlet name is the same as the name of the class in the source code,
which extends the MIDlet class, otherwise the application won’t run.
4) Another window pops up where it is required to select a target platform. Select 'MIDP
1.0' from the drop down list.
5) After clicking OK, the project is created; and the Wireless Toolkit tells that the name
of the folder where source code files are created. The path of the source code folder is
displayed in the debug output window.
Creating and Compiling the DatagramServer source files
The Wireless Toolkit does not come with an IDE by default so Use any IDE or a text
editor like Notepad.
1) Create a new text file called DatagramServer.java in the source folder of the project.
The exact path of this folder is displayed in the Wireless Toolkit window.
2) Paste contents DatagramServer.java from into the source file.
Running your Server application on the Phone simulator
1) After compiling the project successfully, click on the Run button in the Wireless
Toolkit window.
2) A graphical window depicting a phone handset will appear with the name of your
application highlighted on its screen as shown below.
3) To start the application, click on the right soft-key (marked with a dot) below the
‘Launch’ command.
4) The phone simulator might ask if it is OK to run the network application. Select ‘Yes’
by clicking on the appropriate soft-key. The server is now up and running.
5) Keep the server running during the creation, compilation and running of the
Datagram Client application.
Source code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
/**
* @author ADMIN
*/
public class DatagramServer extends MIDlet implements CommandListener{
public Form form1;
public Form form2;
public Command startCommand;
public Command refreshCommand;
public Command exitCommand;
public Display display;
public StringItem st;
public DatagramServer()
{
display=Display.getDisplay(this);
startCommand=new Command("Start",Command.OK,1);
refreshCommand=new Command("Refresh",Command.OK,1);
exitCommand=new Command("Exit",Command.EXIT,1);
st=new StringItem(" "," ");
form1 =new Form("DataGramserver");
form2=new Form("Ready to receive Messages");
form1.addCommand(startCommand);
form1.setCommandListener(this);
form2.addCommand(refreshCommand);
form2.addCommand(exitCommand);
form2.setCommandListener(this);
}
public void startApp() {
display.setCurrent(form1);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command cmd,Displayable displayable)
{
if(displayable==form1)
{
if(cmd==startCommand)
{
try {
DatagramConnection dgc = (DatagramConnection)
Connector.open("datagram://:9001");
try {
int size = 100;
Datagram datagram = dgc.newDatagram(size);
dgc.receive(datagram);
form2.append(datagram.getData().toString());
} finally {
dgc.close();
}
} catch (Exception x){
x.printStackTrace();
}
display.setCurrent(form2);
}
}
else if(displayable==form2)
{
if(cmd==exitCommand)
{
notifyDestroyed();
}
else if(cmd==refreshCommand)
{
st.setText(" ");
}
}
}
}
-----------------------------------Creating the DatagramClient project
1) Use the same instance of the Wireless Toolkit that is used for creating and compiling
the Datagram Server project.
2) Click on 'New Project...' button.
3) A new window pops up. Enter project name as 'DatagramClient'. Enter MIDlet name
as 'DatagramClient'. Note that the Midlet name is the same as the name of the class in
the source code, which extends the MIDlet class.
4) Another window pops up where one has to select a target platform. Select 'MIDP 1.0'
from the drop down list.
5) After clicking OK, the project is created and the Wireless Toolkit tells where to place
the source code files. The path of the source code folder is displayed in the debug
output window as explained before.
Creating and Compiling the DatagramClient source files
1) Create a new text file called DatagramClient.java in the source folder of the
project.
2) Paste contents DatagramClient.java into the source file.
3) Then click on the Build button in the Wireless Toolkit window. If the compilation is
OK, it will say Build Complete in the window's debug output window, otherwise it will
show the errors. Note: In the source code, use the System.out.println() statement to
output debug information to this window.
Running your Client application on the Phone simulator
1) After compiling the project successfully, click on the Run button in the Wireless
Toolkit window.
2) A graphical window depicting a phone handset will appear with the name of the
application highlighted on its screen.
3) To start the application, click on the right soft-key (marked with a dot) below the
‘Launch’ command.
4) The phone simulator might ask if it is OK to run the network application. Select ‘Yes’
by clicking on the appropriate soft-key. The client is now up and running.
5) When the client executes on the phone simulator, one should see a text box with the
caption 'Message'. Enter any message and press the right soft-key (corresponding to
Send). If the client-server application is working properly, the screen of the server phone
will display the message sent by the client and the client screen will now display a
message sent by the server in response. The response message from the server is the
original client message in reverse.
6) Try various features of the phone simulator including the different look-and feel
options.
Source code
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
/**
* @author ADMIN
*/
public class DatagramClient extends MIDlet implements CommandListener{
public Form form1;
public Display display;
public TextField textfield;
public Command sendCommand;
public DatagramClient()
{
display=Display.getDisplay(this);
form1=new Form("Datagram Client");
sendCommand=new Command("send",Command.OK,1);
textfield=new TextField("Enter Text",null,30,TextField.ANY);
form1.append(textfield);
form1.addCommand(sendCommand);
form1.setCommandListener(this);
}
public void startApp() {
display.setCurrent(form1);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command cmd,Displayable d)
{
if(cmd==sendCommand)
{
try
{
DatagramConnection dgc = (DatagramConnection)
Connector.open("datagram://localhost:9001");
try {
while(true)
{
byte[] payload = textfield.getString().getBytes();
Datagram datagram = dgc.newDatagram(payload, payload.length);
dgc.send(datagram);
}
} finally {
dgc.close();
}
} catch (Exception x) {
x.printStackTrace();
}
}
}
}
Week - 7 Authentication with a Web Server
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.
Source code:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public
public
public
public
public
public
class login extends MIDlet implements CommandListener {
Form form1;
Command okCommand;
Display display;
HttpConnection ht=null;
InputStream ist=null;
public
public
public
public
public
public
{
StringItem st;
TextField t1;
TextField t2;
Alert alert;
Form form2;
login()
display=Display.getDisplay(this);
st=new StringItem(" "," Welcome");
alert =new Alert(" ","Wrong UserName or Password",null,AlertType.INFO);
TextField("UserName"," ",30,TextField.ANY);
t2=new TextField("Password"," ",30,TextField.PASSWORD);
form1=new Form("Login Here");
form2=new Form("Welcome");
okCommand=new Command("Login",Command.OK,1);
form1.addCommand(okCommand);
form1.setCommandListener(this);
t1=new
form1.append(t1);
form1.append(t2);
form2.append(st);
}
public void startApp() {
display.setCurrent(form1);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
public void commandAction(Command cmd,Displayable d)
{
if(cmd==okCommand)
{
try
{
//
String
url="http://192.168.5.19:8080/WebApplication7/index.jsp?t1=101&t2=aaa";
String
url="http://192.168.5.19:8080/WebApplication7/index.jsp?t1="+t1.getString().trim()+"&t2
="+t2
.getString().trim();
//ht=(HttpConnection)Connector.open("http://192.168.5.19:8080/WebApplication7/index.js
p");
ht=(HttpConnection)Connector.open(url);
ist=ht.openInputStream();
byte[] b=new byte[900];
ist.read(b);
String s=new String(b);
s=s.trim();
if(s.equals("ok")) Dept
display.setCurrent(form2);
else
{
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
}
catch(Exception ex)
{
form1.append(ex.toString());
}
}
}
}
Week 10:
World Program Application in Android Using Eclipse
Hello World Program Application in Android Using Eclipse
Hello world program application in Android using eclipse. It is the first step when we develop
any application in any language. Before we create an Android Hello World Project, we need to
`make Virtual Device. It means after we create the android application, where we will run and
test our application? For this we have 2 options. One is a real android device and second option
is a Virtual device (Device Emulator, which android provides by default), To setup the virtual
device, we need to follow the below steps.
1. Open SDK Manager and choose Virtual Devices. Click New... to make a new Virtual
Device.
2. Set the option like the picture below (or you can set on your own option) and click Create
AVD.
3. Okay, that’s all for Virtual Device.
1. Next, open eclipse again. Open FIle > New > Project…. Choose Android Project and then
click Next.
2. Fill the options like 2 pictures below and click Finish.
Note: In the above picture, Target name is selected “Android 2.2”. It is nothing but the android
OS version (if you want to select Android 3.0 or Android 4.0 etc, then you can do that), then its
corresponding API version is 8, so you put the Mini SDK Version as per the Android OS
version. Here the mini SDK Version is 8 as I have selected Android 2.2. Have a look on the
below table for details.
Platform Version
Android 4.2
Android 4.1, 4.1.1
Android 4.0.3, 4.0.4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
API Lev
17
16
15
Platform Version
API Level
VERSION_CODE
Android 4.2
17
JELLY_BEAN_MR1
Android 4.1, 4.1.1
16
JELLY_BEAN
Android
4.0.3,
4.0.4
15
ICE_CREAM_SANDWICH_MR1
Android
4.0,
4.0.1,
4.0.2
14
ICE_CREAM_SANDWICH
Android 3.2
13
HONEYCOMB_MR2
Android 3.1.x
12
HONEYCOMB_MR1
Android 3.0.x
11
HONEYCOMB
Android 2.3.4
10
GINGERBREAD_MR1
Android 2.3.3
10
GINGERBREAD_MR1
Android 2.3.2
9
GINGERBREAD
Android 2.3.1
9
GINGERBREAD
Android 2.3
9
GINGERBREAD
Android 2.2.x
8
FROYO
Android 2.1.x
7
ECLAIR_MR1
Android 2.0.1
6
ECLAIR_0_1
Android 2.0
5
ECLAIR
Android 1.6
4
DONUT
Android 1.5
3
CUPCAKE
Android 1.1
2
BASE_1_1
Android 1.0
1
BASE
Application Name: HelloWorld (You can give name)
Package Name: com.test.helloworld (you can give any name in this format)
Create Activity: HelloWorldApp (You can also give any name; this is your display screen name
here).
3. To test the application, click run button and choose Android Application, if Run As windows
appears. Wait until Virtual Device appears (It’s very slow, depend on your system).
4. Finally, you’ll see something like this. If your emulator opens for the first time, then it will take 5-10 minuts, so
don’t worry. Just wait.
This is your first “Hello World” program in android. You have successfully run the first android
application on a emulator.
Get User Input in Android
.
1. Create an Android Project
To create an android project,
1. Go to File menu, then select new -> project or else click new icon in tool bar.
2. Select wizard as Android->Android Application project and click Next.
3. Create new Application window will be open. Enter Application Name, Project Name
and Package and click Next to continue.
4. Select launcher icon for your application and click Next.
5. Select Activity from given two types as Blank activity and Master Details flow activity.
6. Enter Activity Name, Layout name and other details to create activity.
7. Finally click Finish to complete this step.
Note:
The Blank Activity and Master Detail Flow activity is to capture style property to design good
looking app quickly.
App Layout
After completing above, the layout is created as a resource file in this path
workspace/GetUserInput/res/layout/activity_frm.xml. By default it contains the following code
and we need to work on graphical view of the layout to give control with some basic form
widgets.
<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" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world"
tools:context=".FrmActivity" />
</RelativeLayout>
2. Add TextView for Label
Select Graphical layout view and remove default string and follow the steps below,
1. Drag and drop two Textview(Large, Medium..) from form widget in left panel (One for
label of input and the another one for welcome message)
2. Select Text property in right panel and Browse to add new String. OnClick browse
Resource Chooser window will open.
3. Select “New String..” and enter the String to be displayed and resource identifier and
click OK.
4. Then, choose the newly added resource from ‘Resource Chooser’ and click OK.
Now following code will be created to display Textview,
<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" />
3. Add EditText for User Input
Similarly drag EditText box from list of Text Fields and put it in layout next to label. This box
has the input type of person name. After this, following code will be generated in the xml file.
<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>
4. Add Button for User Submission
To add button, the form widget menu has to be expanded and button can be dragged from there.
Text, text color and background color of the button is changed by ‘Reference chooser’ window
and property bar. After creating the button code will be as follows.
<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" />
5. Button Handler
Till this step, everything is done with design view. But this step is accomplished by adding a
Listener into source file(java) which will be in path
workspace/GetUserInput/src/com/javapapers/android/form/FrmActivity.java This is the Activity
file.
To add Listener following code has to be added,
mButton = (Button)findViewById(R.id.button1);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
....
....
....
}
});

OnClickListener is event handler which will be invoked on clicking the Submit button.
 View class instance is responsible for the handling the event.
6. Read Input from EditBox Control
User input is read by instances of form controls. The input entered by the user is read by
getText() method that is called by Editbox instance mEdit.
Button mButton;
EditText mEdit;
TextView mText;
mEdit
= (EditText)findViewById(R.id.editText1);
mEdit.getText().toString();
And then, the instance of Textview is created to show the welcome message. This will be done
by the following code.
mText = (TextView)findViewById(R.id.textView1);
mText.setText("Welcome "+mEdit.getText().toString()+"!");
Activityfrm.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
import
import
import
import
import
android.os.Bundle;
android.app.Activity;
android.view.View;
android.widget.Button;
android.widget.EditText;
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
the different view layouts in an android mobile application. The six different layouts are
1. Linear Layout
2. Relative Layout
3. Table Layout
4. Grid View
5. Tab Layout
6. List View
Android allows you to create view layouts using simple XML file (we can also create a layout using java
code). All the layouts must be placed in /res/layout folder.
Okay, now lets get started with the view layouts.
1. Linear Layout
In a linear layout, like the name suggests, all the elements are displayed in a linear fashion(below is
an example of the linear layouts), either Horizontally or Vertically and this behavior is set in
android:orientation which is an attribute of the node LinearLayout.
Example of Vertical layout snippet
<LinearLayout android:orientation="vertical"> .... </LinearLayout>
Example of Horizontal layout snippet
<LinearLayout android:orientation="horizontal"> .... </LinearLayout>
Now that we know the two types of linear layouts, here are the steps you need to follow to create
them
1. Create a new project File -> New -> Android Project
2. In Package Explorer right click on res/layout folder and create a new Android XML File and name it
as you wish. I am naming it as “linear_layout.xml”
res/layout -> Right Click -> New -> Android XML File
3. Now open newly created xml file (in my case “linear_layout.xml”) and type the following code.
<?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>
4. To set this newly created view as the initial view of your app, Open your MainActivity.java file. You
would see the following line inside the onCreate function setContentView(R.layout.main). Change
R.layout.main to R.layout.yourlinearviewname. In my case its R.layout.linear_layout
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);
}
}
5. To run the application, right click on the project -> Run As -> 1. Android Application. You
should see your newly created linear layout in the emulator.
2. Relative Layout
In a relative layout every element arranges itself relative to other elements or a parent element.
As an example, lets consider the layout defined below. The “Cancel” button is placed relatively, to the
right of the “Login” button parallely. Here is the code snippet that achieves the mentioned alignment
(Right of Login button parallely)
Example code snippet
<Button android:id="@+id/btnLogin" ..></Button>
<Button android:layout_toRightOf="@id/btnLogin"
android:layout_alignTop="@id/btnLogin" ..></Button>
Here are the steps to create a relative layout
1. Create a new project File -> New -> Android Project
2. In Package Explorer right click on res/layout folder and create a new Android XML File and name it
as you wish. I am naming it as “relative_layout.xml”
res/layout -> Right Click -> New -> Android XML File
3. Now open newly created xml file (in my case “relative_layout.xml”) and type the following code.
<?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>
4. Same like before open your MainActivity.java file and set the layout to your newly created relative
layout file. In my case its R.layout.relative_layout
setContentView(R.layout.relative_layout);
5. To run the application, right click on the project -> Run As -> 1. Android Application. You
should see your newly created relative layout in the emulator.
3. Table Layout
Table layouts in Android works in the same way HTML table layouts work. You can divide your layouts
into rows and columns. Its very easy to understand. The image below should give you an idea.
1. Create a new project File -> New -> Android Project
2. In Package Explorer right click on res/layout folder and create a new Android XML File and name it
as you wish. I am naming it as “table_layout.xml”
res/layout -> Right Click -> New -> Android XML File
3. Now open newly created xml file (in my case “table_layout.xml”) and type the following code.
<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
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"/>
1"
</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>
4. Same like before open your MainActivity.java file and set the layout to your newly created table
layout file. In my case its R.layout.table_layout
setContentView(R.layout.table_layout);
5. To run the application, right click on the project -> Run As -> 1. Android Application. You
should see your newly created table layout in the emulator.