I just wanted to make the fontsize larger. But i could not make it. Then I google it and got a good solution. And eventually I did it.
1. Download it and make a font with this.
http://www.gsmdev.com/projects/font4mobile/
2. Download the zip file named Font59.zip
http://www.59pixels.com/index2.html#
3. And see the example and try it. One more thing I should tell, the font file should be put in the res directory. And edit the line as follows,
.
.
.
bigFont = new Font59("bigFont.fnt");
.
.
.
Showing posts with label j2ME. Show all posts
Showing posts with label j2ME. Show all posts
Tuesday, September 16, 2008
Read a Text File in j2me application
You have to put a file named "help.txt" in the class directory and If WTK is used then the file should be out in res folder.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class ReadDisplayFile extends MIDlet implements CommandListener
{
private Display display; // Reference to Display object
private Form fmMain; // Main form
private Command cmHelp; // Command to show a help file
private Command cmExit; // Command to exit the MIDlet
private Alert alHelp; // Alert to display help file text
public ReadDisplayFile()
{
display = Display.getDisplay(this);
cmHelp = new Command("Help", Command.SCREEN, 1);
cmExit = new Command("Exit", Command.EXIT, 1);
fmMain = new Form("Read File");
fmMain.addCommand(cmExit);
fmMain.addCommand(cmHelp);
fmMain.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(fmMain);
}
public void pauseApp()
{ }
public void destroyApp(boolean unconditional)
{ }
public void commandAction(Command c, Displayable s)
{
if (c == cmHelp)
{
String str;
// Access the resource and read its contents
if ((str = readHelpText()) != null)
{
// Create an Alert to display the help text
alHelp = new Alert("Help", str, null, null);
alHelp.setTimeout(Alert.FOREVER);
display.setCurrent(alHelp, fmMain);
}
}
else if (c == cmExit)
{
destroyApp(false);
notifyDestroyed();
}
}
private String readHelpText()
{
InputStream is = getClass().getResourceAsStream("help.txt");
try
{
StringBuffer sb = new StringBuffer();
int chr, i = 0;
// Read until the end of the stream
while ((chr = is.read()) != -1)
sb.append((char) chr);
return sb.toString();
}
catch (Exception e)
{
System.out.println("Unable to create stream");
}
return null;
}
}
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class ReadDisplayFile extends MIDlet implements CommandListener
{
private Display display; // Reference to Display object
private Form fmMain; // Main form
private Command cmHelp; // Command to show a help file
private Command cmExit; // Command to exit the MIDlet
private Alert alHelp; // Alert to display help file text
public ReadDisplayFile()
{
display = Display.getDisplay(this);
cmHelp = new Command("Help", Command.SCREEN, 1);
cmExit = new Command("Exit", Command.EXIT, 1);
fmMain = new Form("Read File");
fmMain.addCommand(cmExit);
fmMain.addCommand(cmHelp);
fmMain.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(fmMain);
}
public void pauseApp()
{ }
public void destroyApp(boolean unconditional)
{ }
public void commandAction(Command c, Displayable s)
{
if (c == cmHelp)
{
String str;
// Access the resource and read its contents
if ((str = readHelpText()) != null)
{
// Create an Alert to display the help text
alHelp = new Alert("Help", str, null, null);
alHelp.setTimeout(Alert.FOREVER);
display.setCurrent(alHelp, fmMain);
}
}
else if (c == cmExit)
{
destroyApp(false);
notifyDestroyed();
}
}
private String readHelpText()
{
InputStream is = getClass().getResourceAsStream("help.txt");
try
{
StringBuffer sb = new StringBuffer();
int chr, i = 0;
// Read until the end of the stream
while ((chr = is.read()) != -1)
sb.append((char) chr);
return sb.toString();
}
catch (Exception e)
{
System.out.println("Unable to create stream");
}
return null;
}
}
Saturday, September 6, 2008
How to sign a MIDlet
I found a nice tutorial that walks you through MIDlet signing process :
MIDlet jar signing (a tutorial) Revised
MIDlet jar signing (a tutorial) Revised
Listening for incoming SMS messages
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.MIDlet;
import javax.wireless.messaging.BinaryMessage;
import javax.wireless.messaging.Message;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.MultipartMessage;
import javax.wireless.messaging.TextMessage;
public class SMSListenerMIDlet extends MIDlet
implements CommandListener, Runnable {
// The port which is listened for incoming messages
private final String PORT = "5000";
private Form mainForm;
private Command startCommand;
private Command stopCommand;
private Command exitCommand;
private MessageConnection connection;
private boolean listening;
public SMSListenerMIDlet() {
mainForm = new Form("SMS Listener");
startCommand = new Command("Start listening", Command.ITEM, 0);
mainForm.addCommand(startCommand);
stopCommand = new Command("Stop listening", Command.ITEM, 1);
mainForm.addCommand(stopCommand);
exitCommand = new Command("Exit", Command.EXIT, 1);
mainForm.addCommand(exitCommand);
mainForm.setCommandListener(this);
}
public void startApp() {
// The initial display is the main form
Display.getDisplay(this).setCurrent(mainForm);
}
public void pauseApp() {
// No implementation required
}
public void destroyApp(boolean unconditional) {
// Stop listening
stopListening();
}
public void commandAction(Command command, Displayable displayable) {
if (command == exitCommand) {
// Exit the MIDlet
destroyApp(true);
notifyDestroyed();
} else if (command == startCommand) {
startListening();
} else if (command == stopCommand) {
stopListening();
}
}
private void startListening() {
// If we are already listening, no need to start again
if (listening) {
return;
}
try {
// Open the connection to the specified port
connection = (MessageConnection)Connector.open("sms://:" + PORT);
} catch (IOException ex) {
return;
}
// Create a listener thread and start listening
Thread listenerThread = new Thread(this);
listening = true;
listenerThread.start();
mainForm.append("Listener started.\n");
}
private void stopListening() {
// If we are not listening, no need to do anything
if (!listening) {
return;
}
if (connection != null) {
try {
// Close the message connection
connection.close();
connection = null;
} catch (IOException ex) {
// TODO: Exception handling
}
}
listening = false;
mainForm.append("Listener stopped.\n");
}
public void run() {
while (listening) {
try {
// Receive all incoming messages to the specified port. The
// receive() method will block until there is a message
// available.
Message message = connection.receive();
if (message != null) {
mainForm.append("Message received.\n");
processMessage(message);
}
} catch (IOException ex) {
// Stop listening
stopListening();
}
}
}
private void processMessage(Message message) {
if (message instanceof TextMessage) {
processTextMessage((TextMessage)message);
} else if (message instanceof BinaryMessage) {
processBinaryMessage((BinaryMessage)message);
} else if (message instanceof MultipartMessage) {
processMultipartMessage((MultipartMessage)message);
}
}
private void processTextMessage(TextMessage message) {
String text = message.getPayloadText();
StringItem textItem = new StringItem("Text", text);
mainForm.append(textItem);
}
/**
* Processes a binary message.
*/
private void processBinaryMessage(BinaryMessage binaryMessage) {
// Not implemented
}
/**
* Processes a multipart message.
*/
private void processMultipartMessage(MultipartMessage multipartMessage) {
// Not implemented
}
}
import javax.microedition.io.Connector;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.MIDlet;
import javax.wireless.messaging.BinaryMessage;
import javax.wireless.messaging.Message;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.MultipartMessage;
import javax.wireless.messaging.TextMessage;
public class SMSListenerMIDlet extends MIDlet
implements CommandListener, Runnable {
// The port which is listened for incoming messages
private final String PORT = "5000";
private Form mainForm;
private Command startCommand;
private Command stopCommand;
private Command exitCommand;
private MessageConnection connection;
private boolean listening;
public SMSListenerMIDlet() {
mainForm = new Form("SMS Listener");
startCommand = new Command("Start listening", Command.ITEM, 0);
mainForm.addCommand(startCommand);
stopCommand = new Command("Stop listening", Command.ITEM, 1);
mainForm.addCommand(stopCommand);
exitCommand = new Command("Exit", Command.EXIT, 1);
mainForm.addCommand(exitCommand);
mainForm.setCommandListener(this);
}
public void startApp() {
// The initial display is the main form
Display.getDisplay(this).setCurrent(mainForm);
}
public void pauseApp() {
// No implementation required
}
public void destroyApp(boolean unconditional) {
// Stop listening
stopListening();
}
public void commandAction(Command command, Displayable displayable) {
if (command == exitCommand) {
// Exit the MIDlet
destroyApp(true);
notifyDestroyed();
} else if (command == startCommand) {
startListening();
} else if (command == stopCommand) {
stopListening();
}
}
private void startListening() {
// If we are already listening, no need to start again
if (listening) {
return;
}
try {
// Open the connection to the specified port
connection = (MessageConnection)Connector.open("sms://:" + PORT);
} catch (IOException ex) {
return;
}
// Create a listener thread and start listening
Thread listenerThread = new Thread(this);
listening = true;
listenerThread.start();
mainForm.append("Listener started.\n");
}
private void stopListening() {
// If we are not listening, no need to do anything
if (!listening) {
return;
}
if (connection != null) {
try {
// Close the message connection
connection.close();
connection = null;
} catch (IOException ex) {
// TODO: Exception handling
}
}
listening = false;
mainForm.append("Listener stopped.\n");
}
public void run() {
while (listening) {
try {
// Receive all incoming messages to the specified port. The
// receive() method will block until there is a message
// available.
Message message = connection.receive();
if (message != null) {
mainForm.append("Message received.\n");
processMessage(message);
}
} catch (IOException ex) {
// Stop listening
stopListening();
}
}
}
private void processMessage(Message message) {
if (message instanceof TextMessage) {
processTextMessage((TextMessage)message);
} else if (message instanceof BinaryMessage) {
processBinaryMessage((BinaryMessage)message);
} else if (message instanceof MultipartMessage) {
processMultipartMessage((MultipartMessage)message);
}
}
private void processTextMessage(TextMessage message) {
String text = message.getPayloadText();
StringItem textItem = new StringItem("Text", text);
mainForm.append(textItem);
}
/**
* Processes a binary message.
*/
private void processBinaryMessage(BinaryMessage binaryMessage) {
// Not implemented
}
/**
* Processes a multipart message.
*/
private void processMultipartMessage(MultipartMessage multipartMessage) {
// Not implemented
}
}
Getting Cell ID in Java ME
When the MIDlet is run in either a Series 40 or S60 device, a cell ID should be shown on the Form (one will have a numeric value and another will have 'null').
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class CellIDMIDlet extends MIDlet implements CommandListener {
private Form form;
private Command exitCommand;
private String S40_cell_id; // Series 40 cell id property
private String S60_cell_id; // S60 cell id property
public void startApp() {
form = new Form("Getting Cell ID");
S40_cell_id = System.getProperty("Cell-ID");
S60_cell_id = System.getProperty("com.nokia.mid.cellid");
form.append("Series 40 devices: " + S40_cell_id + "\n");
form.append("S60 devices: " + S60_cell_id);
exitCommand = new Command("Exit", Command.EXIT, 1);
form.setCommandListener(this);
form.addCommand(exitCommand);
Display.getDisplay(this).setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if (c == exitCommand) this.notifyDestroyed();
}
}
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class CellIDMIDlet extends MIDlet implements CommandListener {
private Form form;
private Command exitCommand;
private String S40_cell_id; // Series 40 cell id property
private String S60_cell_id; // S60 cell id property
public void startApp() {
form = new Form("Getting Cell ID");
S40_cell_id = System.getProperty("Cell-ID");
S60_cell_id = System.getProperty("com.nokia.mid.cellid");
form.append("Series 40 devices: " + S40_cell_id + "\n");
form.append("S60 devices: " + S60_cell_id);
exitCommand = new Command("Exit", Command.EXIT, 1);
form.setCommandListener(this);
form.addCommand(exitCommand);
Display.getDisplay(this).setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if (c == exitCommand) this.notifyDestroyed();
}
}
Sunday, August 10, 2008
A Simple example of PIM in J2ME application [Source Code]
import java.util.Enumeration;
import javax.microedition.pim.*;
public class PIMRunner extends Thread {
private PIMTest midlet;
public PIMRunner(PIMTest midlet) {
this.midlet = midlet;
}
public void run() {
try {
ContactList addressbook = (ContactList) (PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY));
Contact contact = null;
Enumeration items = addressbook.items();
while (items.hasMoreElements()) {
contact = (Contact) (items.nextElement());
String nm[] = contact.getStringArray(Contact.NAME, 0);
if (nm[0] != null)
midlet.addMsg("Name:" + nm[0]);
else
midlet.addMsg("Name:" + nm[1]);
int count = contact.countValues(Contact.TEL);
for (int i = 0; i < count; i++) {
String tnum = contact.getString(Contact.TEL, i);
midlet.addMsg("Telephone:" + tnum );
}
midlet.addMsg("\n");
}
} catch (Exception e) {
midlet.addMsg(e.getMessage());
e.printStackTrace();
}
}
}
import javax.microedition.pim.*;
public class PIMRunner extends Thread {
private PIMTest midlet;
public PIMRunner(PIMTest midlet) {
this.midlet = midlet;
}
public void run() {
try {
ContactList addressbook = (ContactList) (PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY));
Contact contact = null;
Enumeration items = addressbook.items();
while (items.hasMoreElements()) {
contact = (Contact) (items.nextElement());
String nm[] = contact.getStringArray(Contact.NAME, 0);
if (nm[0] != null)
midlet.addMsg("Name:" + nm[0]);
else
midlet.addMsg("Name:" + nm[1]);
int count = contact.countValues(Contact.TEL);
for (int i = 0; i < count; i++) {
String tnum = contact.getString(Contact.TEL, i);
midlet.addMsg("Telephone:" + tnum );
}
midlet.addMsg("\n");
}
} catch (Exception e) {
midlet.addMsg(e.getMessage());
e.printStackTrace();
}
}
}
Wednesday, August 6, 2008
Bigger TextField in J2ME application [Source Code]
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;
public class TextFieldTest extends MIDlet implements CommandListener {
private Display display;
private Form form;
private Command exitCommand;
private TextField text1;
public void startApp() {
display=Display.getDisplay(this);
form=new Form("");
text1=new TextField("","",50,TextField.ANY);
text1.setPreferredSize(100,200);
form.append(text1);
exitCommand=new Command("Exit",Command.EXIT,0);
form.addCommand(exitCommand);
form.setCommandListener(this);
display.setCurrent(form);
}
protected void pauseApp() {
}
protected void destroyApp(boolean arg0) {
}
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
}
}
}
import javax.microedition.lcdui.*;
public class TextFieldTest extends MIDlet implements CommandListener {
private Display display;
private Form form;
private Command exitCommand;
private TextField text1;
public void startApp() {
display=Display.getDisplay(this);
form=new Form("");
text1=new TextField("","",50,TextField.ANY);
text1.setPreferredSize(100,200);
form.append(text1);
exitCommand=new Command("Exit",Command.EXIT,0);
form.addCommand(exitCommand);
form.setCommandListener(this);
display.setCurrent(form);
}
protected void pauseApp() {
}
protected void destroyApp(boolean arg0) {
}
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
}
}
}
Use of POST Method to HTTP Server in J2ME application
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class HttpPostTest extends MIDlet implements CommandListener,Runnable {
private Display display;
private Form form;
private Command exitCommand;
private Command postCommand;
private TextField text1;
public void startApp() {
display = Display.getDisplay(this);
form = new Form("");
text1 = new TextField("Name:", "", 50, TextField.ANY);
form.append(text1);
exitCommand = new Command("Exit", Command.EXIT, 0);
postCommand = new Command("Post", Command.SCREEN, 0);
form.addCommand(exitCommand);
form.addCommand(postCommand);
form.setCommandListener(this);
display.setCurrent(form);
}
protected void pauseApp() {
}
protected void destroyApp(boolean arg0) {
}
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == postCommand) {
Thread t=new Thread(this);
t.start();
}
}
public void run(){
try{
httpPost();
}catch(IOException e){
showAlert(e.getMessage());
}
}
private void showAlert(String s) {
Alert a = new Alert("Exception", s, null, null);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a, form);
}
public void httpPost() throws IOException {
HttpConnection http = null;
OutputStream oStrm = null;
InputStream iStrm = null;
String url = "http://127.0.0.1:4040/posttest.php";
try {
http = (HttpConnection) Connector.open(url);
oStrm = http.openOutputStream();
System.out.println("outputstream opened");
http.setRequestMethod(HttpConnection.POST);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// If you experience connection/IO problems, try
// removing the comment from the following line
// http.setRequestProperty("Connection", "close");
byte data[] = ("name=" + text1.getString()).getBytes();
oStrm.write(data);
System.out.println("written");
//iStrm = http.openInputStream();
System.out.println("input stream opened");
int respCode = http.getResponseCode();
if (respCode == http.HTTP_OK) {
StringBuffer sb = new StringBuffer();
iStrm = http.openDataInputStream();
int chr;
while ((chr = iStrm.read()) != -1)
sb.append((char) chr);
System.out.println(sb.toString());
showAlert(sb.toString());
}
} finally {
if (iStrm != null)
iStrm.close();
if (oStrm != null)
oStrm.close();
if (http != null)
http.close();
}
}
}
PHP CODE:
< ? PHP
$name=$_POST['name'];
print "Wellcome ".$name;
?>
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class HttpPostTest extends MIDlet implements CommandListener,Runnable {
private Display display;
private Form form;
private Command exitCommand;
private Command postCommand;
private TextField text1;
public void startApp() {
display = Display.getDisplay(this);
form = new Form("");
text1 = new TextField("Name:", "", 50, TextField.ANY);
form.append(text1);
exitCommand = new Command("Exit", Command.EXIT, 0);
postCommand = new Command("Post", Command.SCREEN, 0);
form.addCommand(exitCommand);
form.addCommand(postCommand);
form.setCommandListener(this);
display.setCurrent(form);
}
protected void pauseApp() {
}
protected void destroyApp(boolean arg0) {
}
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == postCommand) {
Thread t=new Thread(this);
t.start();
}
}
public void run(){
try{
httpPost();
}catch(IOException e){
showAlert(e.getMessage());
}
}
private void showAlert(String s) {
Alert a = new Alert("Exception", s, null, null);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a, form);
}
public void httpPost() throws IOException {
HttpConnection http = null;
OutputStream oStrm = null;
InputStream iStrm = null;
String url = "http://127.0.0.1:4040/posttest.php";
try {
http = (HttpConnection) Connector.open(url);
oStrm = http.openOutputStream();
System.out.println("outputstream opened");
http.setRequestMethod(HttpConnection.POST);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// If you experience connection/IO problems, try
// removing the comment from the following line
// http.setRequestProperty("Connection", "close");
byte data[] = ("name=" + text1.getString()).getBytes();
oStrm.write(data);
System.out.println("written");
//iStrm = http.openInputStream();
System.out.println("input stream opened");
int respCode = http.getResponseCode();
if (respCode == http.HTTP_OK) {
StringBuffer sb = new StringBuffer();
iStrm = http.openDataInputStream();
int chr;
while ((chr = iStrm.read()) != -1)
sb.append((char) chr);
System.out.println(sb.toString());
showAlert(sb.toString());
}
} finally {
if (iStrm != null)
iStrm.close();
if (oStrm != null)
oStrm.close();
if (http != null)
http.close();
}
}
}
PHP CODE:
< ? PHP
$name=$_POST['name'];
print "Wellcome ".$name;
?>
Use GET Method to communicate with a HTTP Server from J2ME application
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class HttpGetTest extends MIDlet {
private Display display;
public HttpGetTest() {
try {
getBirthdayFromNameUsingGet();
}
catch (IOException e) {
System.out.println("IOException " + e.toString());
}
}
public void startApp() {
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void getBirthdayFromNameUsingGet() throws IOException {
HttpConnection httpConn = null;
String url = "http://127.0.0.1/dbtest.php?user_name=sadat&password=sadat&prov_code=A";
//String url="http://www.google.com.bd/";
InputStream is = null;
OutputStream os = null;
try {
// Open an HTTP Connection object
httpConn = (HttpConnection)Connector.open(url);
// Setup HTTP Request
httpConn.setRequestMethod(HttpConnection.GET);
httpConn.setRequestProperty("User-Agent","Profile/MIDP-1.0 Confirguration/CLDC-1.0");
/** Initiate connection and check for the response code. If the
response code is HTTP_OK then get the content from the target
**/
int respCode = httpConn.getResponseCode();
if (respCode == httpConn.HTTP_OK) {
StringBuffer sb = new StringBuffer();
os = httpConn.openOutputStream();
is = httpConn.openDataInputStream();
int chr;
while ((chr = is.read()) != -1)
sb.append((char) chr);
// Web Server just returns the birthday in mm/dd/yy format.
System.out.println( sb.toString());
}
else {
System.out.println("Error in opening HTTP Connection. Error#" + respCode);
}
} finally {
if(is!= null)
is.close();
if(os != null)
os.close();
if(httpConn != null)
httpConn.close();
}
}
}
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class HttpGetTest extends MIDlet {
private Display display;
public HttpGetTest() {
try {
getBirthdayFromNameUsingGet();
}
catch (IOException e) {
System.out.println("IOException " + e.toString());
}
}
public void startApp() {
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void getBirthdayFromNameUsingGet() throws IOException {
HttpConnection httpConn = null;
String url = "http://127.0.0.1/dbtest.php?user_name=sadat&password=sadat&prov_code=A";
//String url="http://www.google.com.bd/";
InputStream is = null;
OutputStream os = null;
try {
// Open an HTTP Connection object
httpConn = (HttpConnection)Connector.open(url);
// Setup HTTP Request
httpConn.setRequestMethod(HttpConnection.GET);
httpConn.setRequestProperty("User-Agent","Profile/MIDP-1.0 Confirguration/CLDC-1.0");
/** Initiate connection and check for the response code. If the
response code is HTTP_OK then get the content from the target
**/
int respCode = httpConn.getResponseCode();
if (respCode == httpConn.HTTP_OK) {
StringBuffer sb = new StringBuffer();
os = httpConn.openOutputStream();
is = httpConn.openDataInputStream();
int chr;
while ((chr = is.read()) != -1)
sb.append((char) chr);
// Web Server just returns the birthday in mm/dd/yy format.
System.out.println( sb.toString());
}
else {
System.out.println("Error in opening HTTP Connection. Error#" + respCode);
}
} finally {
if(is!= null)
is.close();
if(os != null)
os.close();
if(httpConn != null)
httpConn.close();
}
}
}
Tuesday, August 5, 2008
Use of RadioButton / ChoiceGroup in J2ME application
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;
public class RadioButtonTest extends MIDlet implements CommandListener {
private Display display;
private Form form;
private Command exitCommand;
private ChoiceGroup movies;
private Command process;
public void startApp() {
display = Display.getDisplay(this);
form = new Form("");
movies = new ChoiceGroup("Select Movies You Like to See", Choice.EXCLUSIVE);
movies.append("A", null);
movies.append("B", null);
form.append(movies);
process = new Command("Process", Command.SCREEN, 2);
exitCommand = new Command("Exit", Command.EXIT, 0);
form.addCommand(exitCommand);
form.addCommand(process);
form.setCommandListener(this);
display.setCurrent(form);
}
protected void pauseApp() {
}
protected void destroyApp(boolean arg0) {
}
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == process) {
form.append(new StringItem("", movies.getSelectedIndex()==0?"true":"false" ));
}
}
}
import javax.microedition.lcdui.*;
public class RadioButtonTest extends MIDlet implements CommandListener {
private Display display;
private Form form;
private Command exitCommand;
private ChoiceGroup movies;
private Command process;
public void startApp() {
display = Display.getDisplay(this);
form = new Form("");
movies = new ChoiceGroup("Select Movies You Like to See", Choice.EXCLUSIVE);
movies.append("A", null);
movies.append("B", null);
form.append(movies);
process = new Command("Process", Command.SCREEN, 2);
exitCommand = new Command("Exit", Command.EXIT, 0);
form.addCommand(exitCommand);
form.addCommand(process);
form.setCommandListener(this);
display.setCurrent(form);
}
protected void pauseApp() {
}
protected void destroyApp(boolean arg0) {
}
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == process) {
form.append(new StringItem("", movies.getSelectedIndex()==0?"true":"false" ));
}
}
}
Use CheckBox / ChoiceGroup in j2ME application
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
public class CheckBoxTest extends MIDlet implements CommandListener {
private Display display;
private Form form;
private Command exitCommand;
private ChoiceGroup movies;
private Command process;
public void startApp() {
display = Display.getDisplay(this);
form = new Form("");
movies = new ChoiceGroup("Select Movies You Like to See", Choice.MULTIPLE);
movies.append("A", null);
movies.append("B", null);
form.append(movies);
process = new Command("Process", Command.SCREEN, 2);
exitCommand = new Command("Exit", Command.EXIT, 0);
form.addCommand(exitCommand);
form.addCommand(process);
form.setCommandListener(this);
display.setCurrent(form);
}
protected void pauseApp() {
}
protected void destroyApp(boolean arg0) {
}
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == process) {
boolean picks[] = new boolean[movies.size()];
StringItem message[] = new StringItem[movies.size()];
movies.getSelectedFlags(picks);
for (int i = 0; i < picks.length; i++) {
if (picks[i]) {
message[i] = new StringItem("", movies.getString(i) + "\n");
form.append(message[i]);
}
}
}
}
}
import javax.microedition.midlet.MIDlet;
public class CheckBoxTest extends MIDlet implements CommandListener {
private Display display;
private Form form;
private Command exitCommand;
private ChoiceGroup movies;
private Command process;
public void startApp() {
display = Display.getDisplay(this);
form = new Form("");
movies = new ChoiceGroup("Select Movies You Like to See", Choice.MULTIPLE);
movies.append("A", null);
movies.append("B", null);
form.append(movies);
process = new Command("Process", Command.SCREEN, 2);
exitCommand = new Command("Exit", Command.EXIT, 0);
form.addCommand(exitCommand);
form.addCommand(process);
form.setCommandListener(this);
display.setCurrent(form);
}
protected void pauseApp() {
}
protected void destroyApp(boolean arg0) {
}
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == process) {
boolean picks[] = new boolean[movies.size()];
StringItem message[] = new StringItem[movies.size()];
movies.getSelectedFlags(picks);
for (int i = 0; i < picks.length; i++) {
if (picks[i]) {
message[i] = new StringItem("", movies.getString(i) + "\n");
form.append(message[i]);
}
}
}
}
}
Memory Information of JVM in mobile device [Source Code]
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;
public class MemoryInformation extends MIDlet implements CommandListener {
private Display display;
private Form form;
private Command exitCommand;
public void startApp() {
display = Display.getDisplay(this);
form = new Form("");
exitCommand = new Command("Exit", Command.EXIT, 0);
form.addCommand(exitCommand);
form.setCommandListener(this);
Runtime rtime = Runtime.getRuntime();
form.append("Total memory: " + rtime.totalMemory());
form.append("Free memory: " + rtime.freeMemory());
System.out.println("Total memory: " + rtime.totalMemory());
System.out.println("Free memory: " + rtime.freeMemory());
display.setCurrent(form);
}
protected void pauseApp() {
}
protected void destroyApp(boolean arg0) {
}
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
}
}
}
import javax.microedition.lcdui.*;
public class MemoryInformation extends MIDlet implements CommandListener {
private Display display;
private Form form;
private Command exitCommand;
public void startApp() {
display = Display.getDisplay(this);
form = new Form("");
exitCommand = new Command("Exit", Command.EXIT, 0);
form.addCommand(exitCommand);
form.setCommandListener(this);
Runtime rtime = Runtime.getRuntime();
form.append("Total memory: " + rtime.totalMemory());
form.append("Free memory: " + rtime.freeMemory());
System.out.println("Total memory: " + rtime.totalMemory());
System.out.println("Free memory: " + rtime.freeMemory());
display.setCurrent(form);
}
protected void pauseApp() {
}
protected void destroyApp(boolean arg0) {
}
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
}
}
}
Display information of Mobile Devices in J2ME application [Source Code]
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
public class MobileProperties extends MIDlet implements CommandListener {
private Display display;
protected boolean started;
private Command exitCommand;
protected void startApp() {
if (!started) {
display = Display.getDisplay(this);
Canvas canvas = new DummyCanvas();
Form form = new Form("Attributes");
exitCommand = new Command("Exit", Command.EXIT, 0);
form.addCommand(exitCommand);
boolean isColor = display.isColor();
form.append(new StringItem(isColor ? "Colors: " : "Grays: ", String.valueOf(display.numColors())));
form.append(new StringItem("Width: ", String.valueOf(canvas.getWidth())));
form.append(new StringItem("Height: ", String.valueOf(canvas.getHeight())));
form.append(new StringItem("Pointer? ", String.valueOf(canvas.hasPointerEvents())));
form.append(new StringItem("Motion? ", String.valueOf(canvas.hasPointerMotionEvents())));
form.append(new StringItem("Repeat? ", String.valueOf(canvas.hasRepeatEvents())));
form.append(new StringItem("Buffered? ", String.valueOf(canvas.isDoubleBuffered())));
form.setCommandListener(this);
display.setCurrent(form);
started = true;
}
}
protected void pauseApp() {
}
protected void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
notifyDestroyed();
}
}
}
class DummyCanvas extends Canvas {
protected void paint(Graphics g) {
}
}
import javax.microedition.midlet.MIDlet;
public class MobileProperties extends MIDlet implements CommandListener {
private Display display;
protected boolean started;
private Command exitCommand;
protected void startApp() {
if (!started) {
display = Display.getDisplay(this);
Canvas canvas = new DummyCanvas();
Form form = new Form("Attributes");
exitCommand = new Command("Exit", Command.EXIT, 0);
form.addCommand(exitCommand);
boolean isColor = display.isColor();
form.append(new StringItem(isColor ? "Colors: " : "Grays: ", String.valueOf(display.numColors())));
form.append(new StringItem("Width: ", String.valueOf(canvas.getWidth())));
form.append(new StringItem("Height: ", String.valueOf(canvas.getHeight())));
form.append(new StringItem("Pointer? ", String.valueOf(canvas.hasPointerEvents())));
form.append(new StringItem("Motion? ", String.valueOf(canvas.hasPointerMotionEvents())));
form.append(new StringItem("Repeat? ", String.valueOf(canvas.hasRepeatEvents())));
form.append(new StringItem("Buffered? ", String.valueOf(canvas.isDoubleBuffered())));
form.setCommandListener(this);
display.setCurrent(form);
started = true;
}
}
protected void pauseApp() {
}
protected void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
notifyDestroyed();
}
}
}
class DummyCanvas extends Canvas {
protected void paint(Graphics g) {
}
}
Calendar in J2ME application [Source Code]
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;
import java.util.Calendar;
import java.util.Date;
public class CalendarMIDlet extends MIDlet implements CommandListener {
private Display display;
private Form form;
private Command exitCommand;
public void startApp() {
display = Display.getDisplay(this);
form = new Form("");
exitCommand = new Command("Exit", Command.EXIT, 0);
form.addCommand(exitCommand);
form.setCommandListener(this);
display.setCurrent(form);
Calendar cal = Calendar.getInstance();
Date date = new Date();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
System.out.println("Day is " + day + ", month is " + month);
final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000L;
long offset = date.getTime();
offset += 20 * MILLIS_PER_DAY;
date.setTime(offset);
cal.setTime(date);
month = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DAY_OF_MONTH);
System.out.println("In 20 days time, day will " + day + ", month will be " + month);
System.out.println(cal);
}
protected void pauseApp() {
}
protected void destroyApp(boolean arg0) {
}
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
}
}
}
import javax.microedition.lcdui.*;
import java.util.Calendar;
import java.util.Date;
public class CalendarMIDlet extends MIDlet implements CommandListener {
private Display display;
private Form form;
private Command exitCommand;
public void startApp() {
display = Display.getDisplay(this);
form = new Form("");
exitCommand = new Command("Exit", Command.EXIT, 0);
form.addCommand(exitCommand);
form.setCommandListener(this);
display.setCurrent(form);
Calendar cal = Calendar.getInstance();
Date date = new Date();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
System.out.println("Day is " + day + ", month is " + month);
final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000L;
long offset = date.getTime();
offset += 20 * MILLIS_PER_DAY;
date.setTime(offset);
cal.setTime(date);
month = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DAY_OF_MONTH);
System.out.println("In 20 days time, day will " + day + ", month will be " + month);
System.out.println(cal);
}
protected void pauseApp() {
}
protected void destroyApp(boolean arg0) {
}
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
}
}
}
Print today's Date in j2ME application [Source Code]
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import java.util.Date;
public class DateTest extends MIDlet implements CommandListener {
private Display display;
private Form form = new Form("Today's Date");
private Date today = new Date(System.currentTimeMillis());
private Command exit = new Command("Exit", Command.EXIT, 1);
private DateField datefield = new DateField("", DateField.DATE_TIME);
public DateTest() {
display = Display.getDisplay(this);
datefield.setDate(today);
form.append(datefield);
form.addCommand(exit);
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 == exit) {
destroyApp(false);
notifyDestroyed();
}
}
}
import javax.microedition.midlet.MIDlet;
import java.util.Date;
public class DateTest extends MIDlet implements CommandListener {
private Display display;
private Form form = new Form("Today's Date");
private Date today = new Date(System.currentTimeMillis());
private Command exit = new Command("Exit", Command.EXIT, 1);
private DateField datefield = new DateField("", DateField.DATE_TIME);
public DateTest() {
display = Display.getDisplay(this);
datefield.setDate(today);
form.append(datefield);
form.addCommand(exit);
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 == exit) {
destroyApp(false);
notifyDestroyed();
}
}
}
Play Tone while showing Alert in J2ME application [Source Code]
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;
public class AlertSound extends MIDlet implements CommandListener {
private Display display;
private Command cmdExit;
private Command info;
private Command confirmation;
private Command warning;
private Command alarm;
private Command error;
private Form form;
public void startApp() {
display = Display.getDisplay(this);
form = new Form("Alert Tone");
cmdExit = new Command("Exit", Command.EXIT, 0);
form.addCommand(cmdExit);
info = new Command("Information", Command.SCREEN, 0);
form.addCommand(info);
confirmation = new Command("Confirmation", Command.SCREEN, 0);
form.addCommand(confirmation);
warning = new Command("Warning", Command.SCREEN, 0);
form.addCommand(warning);
alarm = new Command("Alarm", Command.SCREEN, 0);
form.addCommand(alarm);
error = new Command("Error", Command.SCREEN, 0);
form.addCommand(error);
form.setCommandListener(this);
display.setCurrent(form);
}
protected void pauseApp() {
}
protected void destroyApp(boolean arg0) {
}
public void commandAction(Command c, Displayable s) {
if (c == info)
AlertType.INFO.playSound(display);
else if (c == confirmation)
AlertType.CONFIRMATION.playSound(display);
else if (c == warning)
AlertType.WARNING.playSound(display);
else if (c == alarm)
AlertType.ALARM.playSound(display);
else if (c == error)
AlertType.ERROR.playSound(display);
else if (c == cmdExit) {
destroyApp(true);
notifyDestroyed();
}
}
}
import javax.microedition.lcdui.*;
public class AlertSound extends MIDlet implements CommandListener {
private Display display;
private Command cmdExit;
private Command info;
private Command confirmation;
private Command warning;
private Command alarm;
private Command error;
private Form form;
public void startApp() {
display = Display.getDisplay(this);
form = new Form("Alert Tone");
cmdExit = new Command("Exit", Command.EXIT, 0);
form.addCommand(cmdExit);
info = new Command("Information", Command.SCREEN, 0);
form.addCommand(info);
confirmation = new Command("Confirmation", Command.SCREEN, 0);
form.addCommand(confirmation);
warning = new Command("Warning", Command.SCREEN, 0);
form.addCommand(warning);
alarm = new Command("Alarm", Command.SCREEN, 0);
form.addCommand(alarm);
error = new Command("Error", Command.SCREEN, 0);
form.addCommand(error);
form.setCommandListener(this);
display.setCurrent(form);
}
protected void pauseApp() {
}
protected void destroyApp(boolean arg0) {
}
public void commandAction(Command c, Displayable s) {
if (c == info)
AlertType.INFO.playSound(display);
else if (c == confirmation)
AlertType.CONFIRMATION.playSound(display);
else if (c == warning)
AlertType.WARNING.playSound(display);
else if (c == alarm)
AlertType.ALARM.playSound(display);
else if (c == error)
AlertType.ERROR.playSound(display);
else if (c == cmdExit) {
destroyApp(true);
notifyDestroyed();
}
}
}
Supported Media fies and protocols in mobile [Source Code]
We can check which file can be shown, played or which protocols are supported in mobile device from J2ME application. Or it can be used whether mp3 files can be run from mobile or NOT.
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.media.*;
public class MediaInformation extends MIDlet implements CommandListener {
private Form mInformationForm;
public void startApp() {
if (mInformationForm == null) {
mInformationForm = new Form("Content types and protocols");
String[] contentTypes = Manager.getSupportedContentTypes(null);
for (int i = 0; i < contentTypes.length; i++) {
String[] protocols = Manager.getSupportedProtocols(contentTypes[i]);
for (int j = 0; j < protocols.length; j++) {
StringItem si = new StringItem(contentTypes[i] + ": ", protocols[j]);
//si.setLayout(Item.LAYOUT_NEWLINE_AFTER);
mInformationForm.append(si);
}
}
Command exitCommand = new Command("Exit", Command.EXIT, 0);
mInformationForm.addCommand(exitCommand);
mInformationForm.setCommandListener(this);
}
Display.getDisplay(this).setCurrent(mInformationForm);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable s) {
notifyDestroyed();
}
}
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.media.*;
public class MediaInformation extends MIDlet implements CommandListener {
private Form mInformationForm;
public void startApp() {
if (mInformationForm == null) {
mInformationForm = new Form("Content types and protocols");
String[] contentTypes = Manager.getSupportedContentTypes(null);
for (int i = 0; i < contentTypes.length; i++) {
String[] protocols = Manager.getSupportedProtocols(contentTypes[i]);
for (int j = 0; j < protocols.length; j++) {
StringItem si = new StringItem(contentTypes[i] + ": ", protocols[j]);
//si.setLayout(Item.LAYOUT_NEWLINE_AFTER);
mInformationForm.append(si);
}
}
Command exitCommand = new Command("Exit", Command.EXIT, 0);
mInformationForm.addCommand(exitCommand);
mInformationForm.setCommandListener(this);
}
Display.getDisplay(this).setCurrent(mInformationForm);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable s) {
notifyDestroyed();
}
}
Play audio/mp3 file from J2ME application [Source Code]
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.media.*;
public class PlayAudio extends MIDlet implements CommandListener, Runnable {
private Display mDisplay;
private List mMainScreen;
public void startApp() {
mDisplay = Display.getDisplay(this);
if (mMainScreen == null) {
mMainScreen = new List("AudioMIDlet", List.IMPLICIT);
mMainScreen.append("From resource", null);
mMainScreen.addCommand(new Command("Exit", Command.EXIT, 0));
mMainScreen.addCommand(new Command("Play", Command.SCREEN, 0));
mMainScreen.setCommandListener(this);
}
mDisplay.setCurrent(mMainScreen);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable s) {
if (c.getCommandType() == Command.EXIT) notifyDestroyed();
else {
Form waitForm = new Form("Loading...");
mDisplay.setCurrent(waitForm);
Thread t = new Thread(this);
t.start();
}
}
public void run() {
playFromResource();
}
private void playFromResource() {
try {
InputStream is = getClass().getResourceAsStream("/home/sadat/wohlamhe.mp3");
Player player = Manager.createPlayer(is,"audio/mpeg");
player.start();
}
catch (Exception e) {
showException(e);
return;
}
mDisplay.setCurrent(mMainScreen);
}
private void showException(Exception e) {
Alert a = new Alert("Exception", e.toString(), null, null);
a.setTimeout(Alert.FOREVER);
mDisplay.setCurrent(a, mMainScreen);
}
}
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.media.*;
public class PlayAudio extends MIDlet implements CommandListener, Runnable {
private Display mDisplay;
private List mMainScreen;
public void startApp() {
mDisplay = Display.getDisplay(this);
if (mMainScreen == null) {
mMainScreen = new List("AudioMIDlet", List.IMPLICIT);
mMainScreen.append("From resource", null);
mMainScreen.addCommand(new Command("Exit", Command.EXIT, 0));
mMainScreen.addCommand(new Command("Play", Command.SCREEN, 0));
mMainScreen.setCommandListener(this);
}
mDisplay.setCurrent(mMainScreen);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable s) {
if (c.getCommandType() == Command.EXIT) notifyDestroyed();
else {
Form waitForm = new Form("Loading...");
mDisplay.setCurrent(waitForm);
Thread t = new Thread(this);
t.start();
}
}
public void run() {
playFromResource();
}
private void playFromResource() {
try {
InputStream is = getClass().getResourceAsStream("/home/sadat/wohlamhe.mp3");
Player player = Manager.createPlayer(is,"audio/mpeg");
player.start();
}
catch (Exception e) {
showException(e);
return;
}
mDisplay.setCurrent(mMainScreen);
}
private void showException(Exception e) {
Alert a = new Alert("Exception", e.toString(), null, null);
a.setTimeout(Alert.FOREVER);
mDisplay.setCurrent(a, mMainScreen);
}
}
Monday, August 4, 2008
Using Interactive Gause in J2ME application [Source Code]
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.Timer;
import java.util.TimerTask;
public class GaugeExample extends MIDlet implements CommandListener{
private Display display;
private Form fmMain;
private Command cmExit;
private Command cmStop;
private Gauge gaProgress;
private Timer tm;
private GuageTimerTask tt;
public GaugeExample() {
display = Display.getDisplay(this);
gaProgress = new Gauge("Gauge Progress", false, 20, 1);
cmExit = new Command("Exit", Command.EXIT, 1);
cmStop = new Command("Stop", Command.STOP, 1);
fmMain = new Form("");
fmMain.append(gaProgress);
fmMain.addCommand(cmStop);
fmMain.setCommandListener(this);
}
public void startApp() {
display.setCurrent(fmMain);
tm = new Timer();
tt = new GuageTimerTask();
tm.scheduleAtFixedRate(tt, 0, 500);
}
public void pauseApp(){ }
public void destroyApp(boolean unconditional) { }
public void commandAction(Command c, Displayable s) {
if (c == cmExit){
destroyApp(false);
notifyDestroyed();
}else if (c == cmStop){
tm.cancel();
fmMain.removeCommand(cmStop);
fmMain.addCommand(cmExit);
gaProgress.setLabel("Progress Cancelled!");
}
}
/*--------------------------------------------------
* Inner Class
*-------------------------------------------------*/
private class GuageTimerTask extends TimerTask {
public final void run() {
if (gaProgress.getValue() < gaProgress.getMaxValue())
gaProgress.setValue(gaProgress.getValue() + 1);
else {
fmMain.removeCommand(cmStop);
fmMain.addCommand(cmExit);
gaProgress.setLabel("Guage Complete!");
cancel();
}
}
}
}
import javax.microedition.lcdui.*;
import java.util.Timer;
import java.util.TimerTask;
public class GaugeExample extends MIDlet implements CommandListener{
private Display display;
private Form fmMain;
private Command cmExit;
private Command cmStop;
private Gauge gaProgress;
private Timer tm;
private GuageTimerTask tt;
public GaugeExample() {
display = Display.getDisplay(this);
gaProgress = new Gauge("Gauge Progress", false, 20, 1);
cmExit = new Command("Exit", Command.EXIT, 1);
cmStop = new Command("Stop", Command.STOP, 1);
fmMain = new Form("");
fmMain.append(gaProgress);
fmMain.addCommand(cmStop);
fmMain.setCommandListener(this);
}
public void startApp() {
display.setCurrent(fmMain);
tm = new Timer();
tt = new GuageTimerTask();
tm.scheduleAtFixedRate(tt, 0, 500);
}
public void pauseApp(){ }
public void destroyApp(boolean unconditional) { }
public void commandAction(Command c, Displayable s) {
if (c == cmExit){
destroyApp(false);
notifyDestroyed();
}else if (c == cmStop){
tm.cancel();
fmMain.removeCommand(cmStop);
fmMain.addCommand(cmExit);
gaProgress.setLabel("Progress Cancelled!");
}
}
/*--------------------------------------------------
* Inner Class
*-------------------------------------------------*/
private class GuageTimerTask extends TimerTask {
public final void run() {
if (gaProgress.getValue() < gaProgress.getMaxValue())
gaProgress.setValue(gaProgress.getValue() + 1);
else {
fmMain.removeCommand(cmStop);
fmMain.addCommand(cmExit);
gaProgress.setLabel("Guage Complete!");
cancel();
}
}
}
}
Fetch Image From PHP Server in J2ME application [Source Code]
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class ImageFetch extends MIDlet implements CommandListener{
private Display display;
private String URL = "http://127.0.0.1:4040/j2me.php";
private Form formImage;
private Command cmdExit;
public ImageFetch() {
try {
display = Display.getDisplay(this);
cmdExit=new Command("Exit",Command.EXIT,0);
Image im = getImage(URL);
formImage = new Form("Simple Image Test");
formImage.append(im);
formImage.addCommand(cmdExit);
formImage.setCommandListener(this);
display.setCurrent(formImage);
} catch (Exception ex) {
System.out.println(ex);
}
}
public void commandAction(Command c, Displayable s) {
destroyApp(true);
notifyDestroyed();
}
public void startApp() {
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
private Image getImage(String url) throws IOException {
ContentConnection connection = (ContentConnection) Connector.open(url);
DataInputStream iStrm = connection.openDataInputStream();
Image im = null;
try {
byte imageData[];
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = iStrm.read()) != -1)
bStrm.write(ch);
imageData = bStrm.toByteArray();
bStrm.close();
im = Image.createImage(imageData, 0, imageData.length);
} finally {
if (iStrm != null)
iStrm.close();
if (connection != null)
connection.close();
}
return (im == null ? null : im);
}
}
PHP CODE
< ?
$filename = "./passport.jpg";
$handle = fopen ($filename, "rb");
$contents = fread ($handle, filesize ($filename));
fclose ($handle);
echo $contents
?>
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class ImageFetch extends MIDlet implements CommandListener{
private Display display;
private String URL = "http://127.0.0.1:4040/j2me.php";
private Form formImage;
private Command cmdExit;
public ImageFetch() {
try {
display = Display.getDisplay(this);
cmdExit=new Command("Exit",Command.EXIT,0);
Image im = getImage(URL);
formImage = new Form("Simple Image Test");
formImage.append(im);
formImage.addCommand(cmdExit);
formImage.setCommandListener(this);
display.setCurrent(formImage);
} catch (Exception ex) {
System.out.println(ex);
}
}
public void commandAction(Command c, Displayable s) {
destroyApp(true);
notifyDestroyed();
}
public void startApp() {
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
private Image getImage(String url) throws IOException {
ContentConnection connection = (ContentConnection) Connector.open(url);
DataInputStream iStrm = connection.openDataInputStream();
Image im = null;
try {
byte imageData[];
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = iStrm.read()) != -1)
bStrm.write(ch);
imageData = bStrm.toByteArray();
bStrm.close();
im = Image.createImage(imageData, 0, imageData.length);
} finally {
if (iStrm != null)
iStrm.close();
if (connection != null)
connection.close();
}
return (im == null ? null : im);
}
}
PHP CODE
< ?
$filename = "./passport.jpg";
$handle = fopen ($filename, "rb");
$contents = fread ($handle, filesize ($filename));
fclose ($handle);
echo $contents
?>
Subscribe to:
Posts (Atom)
search engine
Custom Search