Image Loader : Connector « J2ME « Java Tutorial






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.midlet.MIDlet;

public class J2MEImageLoader extends MIDlet implements CommandListener, Runnable {
  private Display mDisplay;

  private Form mForm = new Form("Connecting...");

  public J2MEImageLoader() {
    mForm.addCommand(new Command("Exit", Command.EXIT, 0));
    mForm.setCommandListener(this);
  }

  public void startApp() {
    mDisplay = Display.getDisplay(this);
    mDisplay.setCurrent(mForm);

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

  public void pauseApp() {
  }

  public void destroyApp(boolean unconditional) {
  }

  public void commandAction(Command c, Displayable s) {
    if (c.getCommandType() == Command.EXIT)
      notifyDestroyed();
  }

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

    try {
      hc = (HttpConnection) Connector.open("http://www.y.com/image.gif");
      int length = (int) hc.getLength();
      byte[] data = null;
      if (length != -1) {
        data = new byte[length];
        in = new DataInputStream(hc.openInputStream());
        in.readFully(data);
      } else {
        int chunkSize = 512;
        int index = 0;
        int readLength = 0;
        in = new DataInputStream(hc.openInputStream());
        data = new byte[chunkSize];
        do {
          if (data.length < index + chunkSize) {
            byte[] newData = new byte[index + chunkSize];
            System.arraycopy(data, 0, newData, 0, data.length);
            data = newData;
          }
          readLength = in.read(data, index, chunkSize);
          index += readLength;
        } while (readLength == chunkSize);
        length = index;
      }
      Image image = Image.createImage(data, 0, length);
      ImageItem imageItem = new ImageItem(null, image, 0, null);
      mForm.append(imageItem);
      mForm.setTitle("Done.");
    } catch (IOException ioe) {
      mForm.setTitle("Error.");
    }
  }
}








31.40.Connector
31.40.1.Image Loader
31.40.2.URL query
31.40.3.Call asp page from J2ME
31.40.4.Http Get with J2ME
31.40.5.Http header
31.40.6.Load image from a URL
31.40.7.Check Http connection returning code
31.40.8.Http post