MIDlet for downloading image from the web
2 min read
2 min read
public void run() {Note, the operation of establishing an HttpConnection, fetching the image etc is done within a separate thread (see best practices). Of course the code above needs some tuning, this is just a simple example to demonstrate the topic.
HttpConnection connection;
try {
connection = (HttpConnection) Connector.open(this.imageUrl);
connection.setRequestMethod(HttpConnection.GET);
Image img = Image.createImage(connection.openInputStream());
//do something with the image
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
package com.tests.images;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.TextField;
import javax.microedition.lcdui.Ticker;
public class ImageForm extends Form implements CommandListener {
private TextField imageUrlField;
private Command loadImage;
public ImageForm() {
super("Image Viewer");
init();
}
private void init() {
imageUrlField = new TextField("Image URL", "", 999, TextField.URL);
this.append(imageUrlField);
loadImage = new Command("Load Image", Command.SCREEN, 1);
this.addCommand(loadImage);
this.setCommandListener(this);
}
public void showLoadedImage(Image image) {
if(this.size() == 2)
this.delete(1);
this.imageUrlField.setString("");
this.append(image);
this.setTicker(null);
}
public void commandAction(Command c, Displayable d) {
if (c == loadImage) {
this.setTicker(new Ticker("loading image"));
ImageLoaderManager imgMan = new ImageLoaderManager(imageUrlField.getString(), this);
Thread t = new Thread(imgMan);
t.start();
}
}
}
class ImageLoaderManager implements Runnable {
private String imageUrl;
private ImageForm parent;
ImageLoaderManager(String imageUrl, ImageForm parent) {
this.imageUrl = imageUrl;
this.parent = parent;
}
public void run() {
HttpConnection connection;
try {
connection = (HttpConnection) Connector.open(this.imageUrl);
connection.setRequestMethod(HttpConnection.GET);
parent.showLoadedImage(Image.createImage(connection.openInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}