Example below displays image from Tomcat server on J2ME device.
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import java.io.*;
import java.util.Vector;
public class ImageMidletServlet extends MIDlet implements CommandListener
{
Display display = null;
Form form = null;
String url = "http://localhost:8080/servlets-examples/images/DSCF0065.JPG";
Command backCommand = new Command("Back", Command.BACK, 0);
Command submitCommand = new Command("Submit", Command.OK, 2);
Command exitCommand = new Command("Exit", Command.STOP, 3);
private Test test;
public ImageMidletServlet() {}
public void startApp() throws MIDletStateChangeException
{
display = Display.getDisplay(this);
form = new Form("Show Image");
form.addCommand(submitCommand);
form.addCommand(exitCommand);
form.setCommandListener(this);
display.setCurrent(form);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable d)
{
if (c == exitCommand)
{
destroyApp(true);
notifyDestroyed();
}
else if (c == backCommand)
{
display.setCurrent(form);
}
else if (c == submitCommand)
{
test = new Test(this);
test.start();
}
}
class Test implements Runnable
{
ImageMidletServlet midlet;
private Display display;
public Test(ImageMidletServlet midlet)
{
this.midlet = midlet;
display = Display.getDisplay(midlet);
}
public void start()
{
Thread t = new Thread(this);
t.start();
}
public void run()
{
DataInputStream is = null;
StringBuffer sb = new StringBuffer();
Image img= null;
try
{
HttpConnection c = (HttpConnection) Connector.open(url);
int len = (int)c.getLength();
if (len > 0)
{
is = c.openDataInputStream();
byte[] data = new byte[len];
is.readFully(data);
img = Image.createImage(data, 0, len);
Form f = new Form("Image");
ImageItem imgItem = new ImageItem("", img,
ImageItem.LAYOUT_NEWLINE_AFTER |
ImageItem.LAYOUT_CENTER, null);
f.append(imgItem);
display.setCurrent(f);
}
else
{
showAlert("length is null");;
}
is.close();
c.close();
}
catch (Exception e)
{
e.printStackTrace();
showAlert(e.getMessage());
}
}
/* Display Error On screen*/
private void showAlert(String err)
{
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
};
}
No comments:
Post a Comment