Google
Showing posts with label JME. Show all posts
Showing posts with label JME. Show all posts

Thursday, February 19, 2009

How to strip HTML Tags





The output is:

Honolulu Tue 5:05 AM
Washington DC Tue 10:05 AM
Oslo Tue 4:05 PM


The important parts:

String stripH = dataH.replaceAll("<.*?>"," ");

The method replaceAll("<.*?>"," ") strips out all HTML tags
by searching for anything with angle brackets ( < > ) and replace it
with a blank space ( " ").

The regular expression <.*?> means match anything within
the angle brackets once. The dot ( . ) means any character.
The quantifier ( * ) means zero or more. The ( ? ) qualifies
the quantifier ( * ) by saying match it once only. The ( *? ) is
also called a 'reluctant' quantifier.

So, it will catch all the following:


and replaces each one with a blank space.


For J2ME, use this:




Assuming :




Call the method as follows:

String stripped = doStripHtml(data);

Note that
you will still need to modify the code before
you can use it in your HTML Parser application. But I
leave that to you to do.

Below is yet another version:


Monday, February 9, 2009

Bluetooth J2ME Server, J2SE Server and J2ME Client - How to Use

In the previous 3 posts, I put up the sources for the following:

1. J2ME Server
2. J2ME Client
3. J2SE Server

How to Use:

Every client communicates with a server.
Server should always listen first, then, only start the
Client.

Therefore, you can use the following combinations:

A. J2ME Server <--> J2ME Client (mobile phone to mobile phone)
B. J2SE Server <--> J2ME Client (PC to mobile phone, or vice versa)

Scenario A can be run on PC in emulator mode for both Server and Client, or,
both Server and Client run on Mobile Phone.Both (Server and Client) must be run
on PC Emultor, or, both transferred to Mobile phone and run from two mobile phones.
One Mobile Phone will run the Server whilst the second Mobile Phone run the client.

Scenario B, Server must be run on PC whilst Client must be run on real Mobile phone.
In order to run J2SE server you must install the Bluecove library first. This library enables
you to access your PC's Bluetooth hardware. As such when you run Scenario B, you are
actually using the PC's real Bluetooth hardware to communcate with a real mobile Phone.

Summary:
To communicate between two mobile phones, use Scenario A
To communicate between PC and mobile phone (or vice versa), use Scenario B

Bluetooth J2SE Server

Use this server with the J2ME Client

/*
* J2SE Server - to start listening from for connections from
* Mobile Phones and receive a string and display it
*/
package j2seserver;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

public class J2SEServer {

public static void main(String[] ags) throws BluetoothStateException, IOException {
new J2SEServer().startServer();
}

private void startServer() throws BluetoothStateException, IOException {
LocalDevice local = LocalDevice.getLocalDevice();
if (!local.setDiscoverable(DiscoveryAgent.GIAC)) {
System.out.println("Failed to change to the " + "discoverable mode");
}

// Create a server connection object to accept
// a connection from a client
StreamConnectionNotifier notifier =
(StreamConnectionNotifier) Connector.open("btspp://localhost:" +
"86b4d249fb8844d6a756ec265dd1f6a3");

// Accept a connection from the client
StreamConnection conn = notifier.acceptAndOpen();

// Open the input to read data from
InputStream in = conn.openInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();

// Read the data sent from the client until
// the end of stream
int data;
while ((data = in.read()) != -1) {
out.write(data);
}

System.out.println(out.toString());
}
}

Bluetooth J2ME Client

Use this client with either J2SE Server OR J2ME Server

/*
* J2ME Client - to sent a string to the J2SE Server
*/
package j2meclient;

import java.io.OutputStream;
import javax.bluetooth.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class J2MEClientMidlet extends MIDlet implements CommandListener, Runnable {

Display d;
Command cmExit, cmConnect;
Form f;
Thread t;
String connString;

public J2MEClientMidlet() {
f = new Form("Client");
cmExit = new Command("Exit", Command.EXIT, 1);
cmConnect = new Command("Connect", Command.ITEM, 2);

f.addCommand(cmExit);
f.addCommand(cmConnect);
f.setCommandListener(this);
}

public void startApp() {
if (d == null) {
d = Display.getDisplay(this);
d.setCurrent(f);
t = new Thread(this);
}
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void commandAction(Command c, Displayable d) {
if (c == cmExit) {
destroyApp(false);
notifyDestroyed();
}
if (c == cmConnect) {
t.start();
}
}

public void run() {
try {
// Retrieve the connection string to connect to
// the server
LocalDevice local =
LocalDevice.getLocalDevice();
DiscoveryAgent agent = local.getDiscoveryAgent();
connString = agent.selectService(
new UUID("86b4d249fb8844d6a756ec265dd1f6a3", false),
ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
} catch (Exception e) {
}

if (connString != null) {

try {
// Connect to the server and send 'Hello, World'
StreamConnection conn = (StreamConnection) Connector.open(connString);
OutputStream out = conn.openOutputStream();
Thread.sleep(2000); //2 secs delay necessary to wait for
//Nokia 3120 to open connection
out.write("Hello, World".getBytes());
out.close();
conn.close();
f.append("Message sent correctly");

} catch (Exception ex) {
f.append("IOException: ");
f.append(ex.getMessage());
}
}
else{
f.append("Unable to locate service");
}
}
}

Bluetooth J2ME Server

Use this Server with the J2ME Client

/*
* J2ME Server Midlet to accept incoming connection and a string
* from the J2ME Client counterpart
*/

package j2meserver;

import java.io.*;
import javax.bluetooth.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class J2MEServerMidlet extends MIDlet implements CommandListener,Runnable{
Form f;
Command cmExit,cmListen;
Thread t;
Display d;
public J2MEServerMidlet(){
f=new Form("J2ME Server");
cmExit=new Command("Exit",Command.EXIT,1);
cmListen=new Command("Listen",Command.SCREEN,2);
f.addCommand(cmExit);
f.addCommand(cmListen);
f.setCommandListener(this);
}
public void startApp() {
if (d == null) {
d = Display.getDisplay(this);
d.setCurrent(f);
t = new Thread(this);
}
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void commandAction(Command c, Displayable d) {
if(c==cmExit){
destroyApp(false);
notifyDestroyed();
}
if(c==cmListen){
t.start();
}
}

public void run() {
try {
startServer();
} catch (BluetoothStateException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}

private void startServer() throws BluetoothStateException, IOException {
LocalDevice local = LocalDevice.getLocalDevice();
if (!local.setDiscoverable(DiscoveryAgent.GIAC)) {
System.out.println("Failed to change to the " + "discoverable mode");
}

// Create a server connection object to accept
// a connection from a client
StreamConnectionNotifier notifier =
(StreamConnectionNotifier) Connector.open("btspp://localhost:" +
"86b4d249fb8844d6a756ec265dd1f6a3");

// Accept a connection from the client
StreamConnection conn = notifier.acceptAndOpen();

// Open the input to read data from
InputStream in = conn.openInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();

// Read the data sent from the client until
// the end of stream
int data;
while ((data = in.read()) != -1) {
out.write(data);
}
f.append("Received: ");
f.append(out.toString());
}
}

Saturday, February 7, 2009

Bluetooth Acronyms

JABWT Stack:




JABWT = Java API for Bluetooth Wireless Technology
BTSPP = BlueTooth Serial Port Profile, as in btspp://localhost
BCC = Bluetooth Control Centre
OBEX = Object Exchange
SDP = Service Discovery Protocol
SDDB = Service Discovery DataBase
L2CAP = Logical Link Control and Adaptation Protocol
GCF = Generic Connection Framework :

Monday, February 2, 2009

HTML Parser - Simple

This html parser searches for the string 'Malaysia' from
the website http://www.google.com.my and displays it:

/*
* By Paul Chin
*/
package htmlparser;

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class HtmlparserMidlet extends MIDlet implements CommandListener, Runnable {

private Display d;
private Form f;
private Command cmExit;

public HtmlparserMidlet() {
cmExit = new Command("Exit", Command.EXIT, 0);
f = new Form("Connecting...");
f.addCommand(cmExit);
f.setCommandListener(this);
}

public void startApp() {
if (d == null) {
d = Display.getDisplay(this);
d.setCurrent(f);

Thread t = new Thread(this);
t.start();
}
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void commandAction(Command c, Displayable d) {
if (c == cmExit) {
destroyApp(false);
notifyDestroyed();
}
}

public void run() {
HttpConnection hc = null;
DataInputStream in = null;
StringBuffer data = new StringBuffer();

String url = "http://www.google.com.my/index.html";

try {
hc = (HttpConnection) Connector.open(url);
in = new DataInputStream(hc.openInputStream());

int ch;
while (true) {
ch = in.read();
if (ch == -1) {
break;
}
data.append((char) ch);
}

//Search for string "Malaysia"
String s = data.toString();
int index = s.indexOf("Malaysia");
String t = s.substring(index, index + 8);


f.append(t);
f.setTitle("Done");
} catch (Exception e) {
}
}
}

J2ME SMTP Client - This one works

I've modified and corrected the errors in the the earlier
version. The code below works. It sends the message:
'TESTMESSAGE FROM INTI' to your email address.
You need to use nslookup to find the SMTP server
for your email domain first and substitue it in
the appropriate places.


/*
* SMTPClient by Paul Chin
*/
package smtpclient;

import java.io.*;
import java.util.Date;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class SMTPClientMidlet extends MIDlet implements CommandListener, Runnable {

SocketConnection sc;
Display d;
Form f;
Command cmExit, cmSend;
InputStream is = null;
OutputStream os = null;
StringBuffer sb = new StringBuffer();
static final String domain = "intipen.edu.my";
static final String smtpServerAdress = "b.mx.mail.yahoo.com";
static final String from_emailAdress = "justacoder@intipen.edu.my";
static final String to_emailAdress = "javarocks@yahoo.com";
Thread t;

public SMTPClientMidlet() {
cmExit = new Command("Exit", Command.EXIT, 0);
cmSend = new Command("Send", Command.SCREEN, 1);


f = new Form("SMTP Client");


f.addCommand(cmExit);
f.addCommand(cmSend);
f.setCommandListener(this);
}

public void startApp() {
if (d == null) {
d = Display.getDisplay(this);
d.setCurrent(f);

t = new Thread(this);
}
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void sendEmail() {
int ch;
byte[] b = new byte[2046];
try {
sc = (SocketConnection) Connector.open("socket://" + smtpServerAdress + ":25");
is = new DataInputStream(sc.openInputStream());

os = sc.openOutputStream();

is.read(b);
// Send SMTP-Commands
os.write(("HELO " + domain + "\r\n").getBytes());
is.read(b);


os.write(("MAIL FROM: <" + from_emailAdress + ">\r\n").getBytes());
is.read(b);


os.write(("RCPT TO: <" + to_emailAdress + ">\r\n").getBytes());
is.read(b);


os.write("DATA\r\n".getBytes());
is.read(b);

os.write(("Date: " + new Date() + "\r\n").getBytes());
os.write(("From: " + from_emailAdress + "\r\n").getBytes());
os.write(("To: " + to_emailAdress + "\r\n").getBytes());
os.write(("Subject: INTI TEST\r\n").getBytes());
os.write(("\r\n").getBytes());
os.write(("TESTMESSAGE FROM INTI \r\n").getBytes());
os.write(".\r\n".getBytes());
is.read(b);

os.write("QUIT\r\n".getBytes());
is.read(b);

System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (sc != null) {
sc.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

}

public void commandAction(Command c, Displayable d) {
if (c == cmExit) {
destroyApp(false);
notifyDestroyed();
}
if (c == cmSend) {
t.start();
}
}

public void run() {
sendEmail();
}
}


Monday, January 19, 2009

Bluetooth on J2SE

http://bluecove.sourceforge.net/

Quick Tutorials

How to quickly install and test your bluetooth
J2SE capability.

1. Download bluecove-2.1.0.jar from http://code.google.com/p/bluecove/

2. Open Netbeans, goto Libraries Menu and add new library.
Navigate to the bluecone-2.1.0.jar and add it as a jar library.
Do not uncompress it. Call it Bluecove in the textfield descriptor.


3. Create a new Java application project and paste this code in:

/**
* Minimal Device Discovery example.
*
* http://bluecove.sourceforge.net/apidocs/overview-summary.html#DeviceDiscovery
*/
package bluetoothremotedevicediscovery;

import java.io.IOException;
import java.util.Vector;
import javax.bluetooth.*;

public class RemoteDeviceDiscovery {

public static final Vector/**/ devicesDiscovered = new Vector();

public static void main(String[] args) throws IOException, InterruptedException {

final Object inquiryCompletedEvent = new Object();

devicesDiscovered.clear();

DiscoveryListener listener = new DiscoveryListener() {

public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
System.out.println("Device " + btDevice.getBluetoothAddress() + " found");
devicesDiscovered.addElement(btDevice);
try {
System.out.println(" name " + btDevice.getFriendlyName(false));
} catch (IOException cantGetDeviceName) {
}
}

public void inquiryCompleted(int discType) {
System.out.println("Device Inquiry completed!");
synchronized (inquiryCompletedEvent) {
inquiryCompletedEvent.notifyAll();
}
}

public void serviceSearchCompleted(int transID, int respCode) {
}

public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
}
};

synchronized (inquiryCompletedEvent) {
boolean started = LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC, listener);
if (started) {
System.out.println("wait for device inquiry to complete...");
inquiryCompletedEvent.wait();
System.out.println(devicesDiscovered.size() + " device(s) found");
}
}
}
}


4. Edit your Project properties Select the Library and then
select the Compile Tab and click on Add Library. Select the Bluecove
library.

5. Just run it and watch the output window. Make sure your bluetooth
is turned on and also your Mobile phone is turned on. It will be
able to detect your mobile phone.


Bluetooth JSR82 Samples:
http://www.jsr82.com/

How to get IP of your mobile phone

Your mobile handset will be connected to the service provider's NAT gateway. The IP that your mobile handset get is a private IP, means that this IP can't be reached from external world.

There are ways to get both your private IP and the IP Address of the NAT gateway.

Getting your IP Address

1)The following snippet will give you your private IP Address.


ServerSocketConnection scn = (ServerSocketConnection)Connector.open("socket://:1234");
System.out.println(scn.getLocalAddress());

Note: This method may return your IP Address as 127.0.0.1 (the loopback address) if the GPRS link has been idle. So always send some data over the connection before testing this.

2)Using the System properties


System.getProperty("microedition.hostname");


3)This is a bit round about method, but is the most guarenteed to work one. If you are trying to connect to your custom server, have the server tell your ip to you. Implement a handshake protocol, where you say "Hello server" and the server replies "Hello client. Your IP is xx.xx.xx.xx".

Getting the IPAddress of the NAT gateway

Service like http://whatismyipaddress.com/ or http://www.lawrencegoetz.com/programs/ipinfo/ or http://www.whatismyip.com/ gives the IP Address it sees when you browse their pages. This will be your NAT IP Address. Just parse the page and get the IP.



http://www.javameblog.com/2007/12/how-to-get-ip-address-of-mobile-using.html

Determining if a string contains substring

String string = "Madam, I am Adam";

// Starts with
boolean b = string.startsWith("Mad"); // true

// Ends with
b = string.endsWith("dam"); // true

// Anywhere
b = string.indexOf("I am") > 0; // true

// To ignore case, regular expressions must be used

// Starts with
b = string.matches("(?i)mad.*");

// Ends with
b = string.matches("(?i).*adam");

// Anywhere

b = string.matches("(?i).*i am.*");


http://www.exampledepot.com/egs/java.lang/HasSubstr.html

Friday, January 2, 2009

Full Screen Mode

Full screen mode is now possible with:

public void startApp() {
if (canvas == null) {
canvas = new practiceCanvas(Display.getDisplay(this));
Command exitCommand = new Command("Exit", Command.EXIT, 0);
canvas.addCommand(exitCommand);
canvas.setFullScreenMode(true);
canvas.setCommandListener(this);
}

// Start up the canvas
canvas.start();
}


However, the older deprecated Nokia UI is available for
download here:

Nokia UI, API

But it is not necessary. Previously to get full screen,
you need to do this:

import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
import java.util.*;
import java.io.*;
import com.nokia.mid.ui.*;

public class practiceCanvas extends FullCanvas implements Runnable{


Now, with MIDP2, no need to extend Nokia's FullCanvas class,
to get fullscreen just set:

canvas.setFullScreenMode(true);

This works for SonyEricsson as well as Nokia.
However, in Nokia, you may need to press keypad 5 for
the fire button, instead of the usual controller center
key

Device Control

However it is a good idea to take a look at the
deprecated Nokia UI to see what device control is available
as replaced by MIDP2, eg,

com.nokia.mid.ui Class DeviceControl

enables vibration, etc...

display.vibrate(int frequency)
frequency is from 1 to 100

Others:

javax.microedition.lcdui.Display.flashBacklight(int).

However, note that when you do:

AlertType.INFO.playSound(display);

the mobile phone may also vibrate. As such it
may be redundant to call display.vibrate();

Note that other S40_6th_Edition_SDK contains other
API specific to Nokia only. If you choose to implement them,
then the program is limited to Nokia.


Thursday, January 1, 2009

How to create transparent background Sprites

1. Assuming you have the following sprite grid file:


and you wish to create a frame sprite out of the two alien in the center
marked by the rectangle.

2. Open up Gimp and select it with the rectangle select tool as
shown below:


3. Copy the selection and paste it into another new canvas:


Note that the canvas is larger than the selection that has just
been pasted into it.

4. To reduce the canvas size until it fits the image, select
Image / AutoCrop Image and you will get this:


5. The next step is to remove the black background, so that
the background is transparent. To do this, you need to merge
the layers so that there is only one layer. Only then can you
select the black background and cut it out. Select Merge Visible
Layers. Then select the black background using Select / By Color
and you should get this:


6. Then simply cut out the selected black background and
you will get this:


The background is now transparent. You can now, create
a sprite out of it. You will need to get the Pixel Dimension.
Select Image / Image Properties to see it:

Note that the Pixel Dimension is 32 x 10.
As such, each sprite frame size should be 16 x 10.

Do this:

alienSprite=new Sprite(Image.createImage("/images/alien.png"),16,10);


Note that you can also find out the Pixell Dimension by hovering
the cursor over the image and watching the px values on the
bottom left of the window.

Tuesday, December 30, 2008

How to calculate FPS

public UFOCanvas(Display d) {
super(true);
display = d;
// Set the frame rate (30 fps)
frameDelay = 33;
}

To get fps:

(1/frameDelay) x 1000
= (1/33)*1000
= 30 fps

Monday, December 15, 2008

World Clock 0.0.38 Released

World Clock Version 0.0.38 is completed.
Download

Splash Screen:

Select Country,City:


Real-time Clock:

Saturday, December 13, 2008

Workaround to List Bug in Nokia SDK 6th Edition

Running the application compiled under SDK 5th edition
on the SDK 6th edition's emulator:


A temporary work-around to the List Bug:

In Netbeans 6.5, compile the application using SDK 5.

Then fire up your SDK 6 emulator (outside of Netbeans 6.5).
Use the File menu, navigate to the dist folder of the Netbeans
project. You will find a .jad and a .jar file there.
Open the .jad file (emulator will then execute the .jar).
The above image is the result. Works like
a charm! This temporary workaround will do for now,
while waiting for Nokia to fix the bug.

Sunday, December 7, 2008

Simplest MultiThreading Hello App in J2ME

Below is the simplest multi-threading application in
J2ME.

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;


public class HelloByThread extends MIDlet implements CommandListener{
private Command exitCommand,sayhelloCommand;
private Display display;
private Form fmMain;
private TextField helloField;

public HelloByThread(){
fmMain=new Form("Main Form");
exitCommand=new Command("Exit",Command.SCREEN,1);
sayhelloCommand=new Command("Say Hello",Command.ITEM,2);
fmMain.addCommand(exitCommand);
fmMain.addCommand(sayhelloCommand);
fmMain.setCommandListener(this);
}

public void startApp() {
display=Display.getDisplay(this);
display.setCurrent(fmMain);
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void commandAction(Command c, Displayable d) {
if(c==sayhelloCommand){
HelloSayer hs=new HelloSayer(this);
hs.start();
}
else if(c==exitCommand){
destroyApp(false);
notifyDestroyed();
}
}

public void sayHello(){
fmMain.append("Hello Paul");
}
}

class HelloSayer implements Runnable{
private HelloByThread hbtMidlet;

public HelloSayer(HelloByThread hbtMidlet){
this.hbtMidlet=hbtMidlet;
}

public void run() {
hbtMidlet.sayHello();
}

public void start() {
Thread thread = new Thread(this);
try
{
thread.start();
}
catch (Exception e)
{
}
}
}

All it does is say Hello Paul. But it does so without
blocking the main System Thread.

Saturday, December 6, 2008

HttpConnection Class

Read this:

The HttpConnection Class by Yu Feng


Then modified my code.

The code below works for Z610i and on my PC emulator,

but fails on my T610 due to failure to open stream:

is = hc.openInputStream();

The commented out part also works on Z610i and
PC Emulator and also fails on my T610 due
to failure to open stream:

in = conn.openInputStream();


package MyMobilePractice2;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
import javax.microedition.io.*;
import java.util.*;



public class Fortune extends MIDlet implements CommandListener {
private Command exitCommand, nextCommand;
private Display display;
private Form screen;
private StringItem fortuneItem;
private Vector fortunes;

public Fortune() {
// Get the Display object for the MIDlet
display = Display.getDisplay(this);
// Create the Exit and Next commands
exitCommand = new Command("Exit", Command.ITEM, 2);
nextCommand = new Command("Next", Command.ITEM, 2);
// Create the main screen form
screen = new Form("Fortune of the Day");
fortuneItem = new StringItem("", "Reading fortunes...");
screen.append(fortuneItem);
// Set the Exit and Next commands for the screen
screen.addCommand(exitCommand);
screen.addCommand(nextCommand);
screen.setCommandListener(this);
// Create the fortunes vector
fortunes = new Vector();
}
public void startApp() throws MIDletStateChangeException {
// Set the current display to the location screen
display.setCurrent(screen);
// Initialize the fortunes vector
readFortunes();
// Show the first random fortune
showFortune();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
}
else if (c == nextCommand) {
// Show the next random fortune
showFortune();
}
}

private void readFortunes(){
StringBuffer data = new StringBuffer();
HttpConnection hc= null;
InputStream is=null;
try{
hc=(HttpConnection)Connector.open("http://putyourwebsite.here/Fortunes.html");
}
catch(Exception e){
Alert httpAlert=new Alert("HTTP","fail",null,AlertType.ERROR);
httpAlert.setTimeout(Alert.FOREVER);
display.setCurrent(httpAlert);
return;
}
try{
is = hc.openInputStream();
}
catch(Exception ex){
Alert streamAlert=new Alert("STREAM","fail",null,AlertType.ERROR);
streamAlert.setTimeout(Alert.FOREVER);
display.setCurrent(streamAlert);
return;
}

// Read a line at a time from the input stream
int ch;
boolean done = false;
try{
while ((ch = is.read()) != -1) {
if (ch != '\n') {
// Read the line a character at a time
data.append((char)ch);
}
else {
// Add the fortune to the fortunes vector
fortunes.addElement(data.toString());
// Clear the string for the next line
data = new StringBuffer();
}
}
}
catch(Exception e){}

}

// private void readFortunes() {
// StreamConnection conn = null;
// InputStream in = null;
// StringBuffer data = new StringBuffer();
// try {
// // Open the HTTP connection
// conn = (StreamConnection)Connector.open("http://192.168.20.3/Fortunes.txt");
// // Obtain an input stream for the connection
// in = conn.openInputStream();
// // Read a line at a time from the input stream
// int ch;
// boolean done = false;
// while ((ch = in.read()) != -1) {
// if (ch != '\n') {
// // Read the line a character at a time
// data.append((char)ch);
// }
// else {
// // Add the fortune to the fortunes vector
// fortunes.addElement(data.toString());
// // Clear the string for the next line
// data = new StringBuffer();
// }
// }
// }
// catch (IOException e) {
// System.err.println("The connection could not be established.");
// }
// }
//
private void showFortune() {
// Check to make sure the fortunes vector isn’t empty
if (!fortunes.isEmpty()) {
// Create and seed the random number generator
Random rand = new Random(Calendar.getInstance().getTime().getTime());
// Set a random fortune
int fortuneNum = Math.abs(rand.nextInt()) % fortunes.size();
fortuneItem.setText((String)fortunes.elementAt(fortuneNum));
}
else
fortuneItem.setText("No fortune!");
}
}

Sunday, November 30, 2008

Focus Tool Version 001 Completed

Bare bones User Interface:



Alerts randomly every 1 to 60 seconds.

Friday, November 28, 2008

Focus Tool Project - Getting the correct image size

To get the correct pixel size for this:


Open Windows Explorer and get the properties of the .png file directly: