1
Display display = null;
String url = "http://188.2.222.253/screenshot.png";    
DataInputStream is = null;
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");      
    GameCanvas gc = null;
    Graphics g = null;
    g.drawImage(img, 0, 0, 0); //NullPointerException
    gc.paint(g);
    display.setCurrent(gc); 
  } 
  else 
  {
    showAlert("length is null");
  }
  is.close();
  c.close();
} 
catch (Exception e) 
{
  e.printStackTrace();
  showAlert(e.getMessage());
}

g.drawImage(img, 0, 0, 0) 抛出 NullPointerException。这意味着 img 为空(http://docs.oracle.com/javame/config/cldc/ref-impl/midp2.0/jsr118/javax/microedition/lcdui/Graphics.html)。我可以将 img 与 ImageItem 和它的 NOT null 一起使用。什么是问题?

4

1 回答 1

0

You are setting Graphics g = null just before you call g.drawImage(img, 0, 0, 0). It is not your img that is null. It is your Graphics object.

You're also setting GameCanvas gc = null 3 lines before you call gc.paint(g) - another NullPointerException.

On top of this, you can't create and draw on a GameCanvas using this approach. GameCanvas is an abstract class. So you need to create your own class which extends GameCanvas - if a GameCanvas is what you want. I'm not sure that's the case either, since you can easily settle for a Form, if all you want is to display a picture.

Try this instead:

img = Image.createImage(data, 0, len);
Form f = new Form("Image");
f.append(img);
display.setCurrent(f);
于 2013-07-29T05:46:24.470 回答