使用检索到的Image时的Java.lang.NullPointerException(除非静态使用方法!)

时间:2010-03-19 17:38:02

标签: java nullpointerexception

在我的MIDLet中,我有一个名为anImg的java类ImageFetcher实例。同样在我的MIDLet中,我有一个命令,简单地说是fetch,一个CommandListener,当检测到fetch被点击时运行下面的函数。此函数应该只从类ImageFetcher的anImg实例运行public getImage(),该实例返回一个图像,然后将此Image附加/设置到显示器上的表单上。 (您可以从Nokia JavaME Wiki中识别getImage()函数!!!)

而不是显示任何图像,这将被写入netbeans中的输出终端: 消息:Java.lang.NullPointerException

但是,如果我将public getImage()更改为public static getImage()并使用ImageFetcher.getImage()替换anImg.getImage(),则图像会成功显示!!!

感谢您对此问题的回复:) 在这次考验之后,我期待着把头发弄回来!

FetchImageApp.java

...
...
public class FetchImageApp() 
extends MIDlet implements CommandListener {

     private ImageFetcher anImg; //this is my ImageFetcher instance, it is assigned within the constructor

     public FetchImageApp(){
         anImg = new ImageFetcher(); //NO IT WASN'T, I knew it was something simple... I feel a fool... but I know we all do it!
     }
...
     private doThis(){
        try {
            Image im;
            if ((im = anImg.getImage()) != null) {
                ImageItem ii = new ImageItem(null, im, ImageItem.LAYOUT_DEFAULT, null);
                // If there is already an image, set (replace) it
                if (form.size() != 0) {
                    form.set(0, ii);
                } else // Append the image to the empty form
                {
                    form.append(ii);
                }
            } else {
                form.append("Unsuccessful download.");
            }
            // Display the form with the image
            display.setCurrent(form);
        } catch (Exception e) {
            System.err.println("Msg: " + e.toString());
        }
     }
...
...
...

ImageFetcher.java

...
...
...
    /*--------------------------------------------------
     * Open connection and download png into a byte array.
     *-------------------------------------------------*/
    public Image getImage() throws IOException {
        String url = "http://kenai.com/attachments/wiki_images/chessgame/java-duke-logo.png";
        ContentConnection connection = (ContentConnection) Connector.open(url);

        // * There is a bug in MIDP 1.0.3 in which read() sometimes returns
        //   an invalid length. To work around this, I have changed the
        //   stream to DataInputStream and called readFully() instead of read()
//    InputStream iStrm = connection.openInputStream();
        DataInputStream iStrm = connection.openDataInputStream();

        ByteArrayOutputStream bStrm = null;
        Image im = null;

        try {
            // ContentConnection includes a length method
            byte imageData[];
            int length = (int) connection.getLength();
            if (length != -1) {
                imageData = new byte[length];

                // Read the png into an array
//        iStrm.read(imageData);
                iStrm.readFully(imageData);
            } else // Length not available...
            {
                bStrm = new ByteArrayOutputStream();

                int ch;
                while ((ch = iStrm.read()) != -1) {
                    bStrm.write(ch);
                }

                imageData = bStrm.toByteArray();
                bStrm.close();
            }

            // Create the image from the byte array
            im = Image.createImage(imageData, 0, imageData.length);
        } finally {
            // Clean up
            if (iStrm != null) {
                iStrm.close();
            }
            if (connection != null) {
                connection.close();
            }
            if (bStrm != null) {
                bStrm.close();
            }
        }
        return (im == null ? null : im);
    }
...
...
...

这是根据请求的侦听器代码:)

public void commandAction(Command c, Displayable d) {
    if (c == doThisCommand) {
        if (c.getLabel().equals("Start")) {
            System.out.println("Started...");
            begin();
            //doThisCommand = new Command("Stop", Command.OK, 2); //ERROR:: After the command is changed to exit the program throws and unhandled excaption.
        } else {
            System.out.println("Stopped...");
            doThisCommand = new Command("Start", Command.OK, 2);
        }
    } else if (c == exitCommand) {
        notifyDestroyed();
    } else {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}

2 个答案:

答案 0 :(得分:1)

你可以张贴你的听众吗?我猜测NPE来自于侦听器使用null的ImageFetcher实例这一事实。取消引用它时会抛出NullPointerException

当您更改为静态方法时不会发生这种情况,因为没有涉及实例。

答案 1 :(得分:1)

如果您在NullPointerException上获得anImg.getImage(),则只表示anImgnull。执行System.out.println(anImg);,您会看到它打印null

要修复它,您需要以某种方式实例化anImg。 E.g。

ImageFetcher anImg = new ImageFetcher();

只有这样你才能访问它并在其上调用方法。