ImageLoaderMIDlet.java Source code

Java tutorial

Introduction

Here is the source code for ImageLoaderMIDlet.java

Source

import java.io.DataInputStream;
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.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.MIDlet;

public class ImageLoaderMIDlet extends MIDlet {
    private Item mItem;

    public void startApp() {
        final Display display = Display.getDisplay(this);

        Form mainForm = new Form("Loading...");
        display.setCurrent(mainForm);

        final Form imageForm = new Form("Image");
        imageForm.addCommand(new Command("Exit", Command.EXIT, 0));
        imageForm.setCommandListener(new CommandListener() {
            public void commandAction(Command c, Displayable s) {
                notifyDestroyed();
            }
        });

        Thread t = new Thread() {
            public void run() {
                try {
                    String URL = "http://localhost/Duke.png";
                    Image image = loadImage(URL);
                    mItem = new ImageItem(null, image, 0, null);
                } catch (IOException ioe) {
                    mItem = new StringItem(null, ioe.toString());
                }
                imageForm.append(mItem);
                display.setCurrent(imageForm);
            }
        };
        t.start();
    }

    public Image loadImage(String url) throws IOException {
        HttpConnection hpc = null;
        DataInputStream dis = null;
        try {
            hpc = (HttpConnection) Connector.open(url);
            int length = (int) hpc.getLength();
            byte[] data = new byte[length];
            dis = new DataInputStream(hpc.openInputStream());
            dis.readFully(data);
            return Image.createImage(data, 0, data.length);
        } finally {
            if (hpc != null)
                hpc.close();
            if (dis != null)
                dis.close();
        }
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }
}