views:

207

answers:

2

Hi there,

This has been doing my head in all day and I have finally decided to resort to asking for help!

In my MIDLet I have an instance of the java class ImageFetcher called anImg. Also within my MIDLet I have a command that simply say's fetch, a CommandListener that when detects fetch was clicked runs the function below. This function should simply run public getImage() from the anImg instance of class ImageFetcher which returns an image and then appends/sets this Image onto the form on the display. (You may recognise the getImage() function from the Nokia JavaME Wiki!!!)

Instead of any image being displayed this is written to the output terminal in netbeans: Msg: Java.lang.NullPointerException

HOWEVER, If I change public getImage() to public static getImage() and replace anImg.getImage() with ImageFetcher.getImage() the image is successfully displayed!!!

Thank you for your replies on this issue :) I look forward to going my hair back after this ordeal!

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);
    }
...
...
...

Here is the listener code as per request :)

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.");
    }
}
+1  A: 

Can you post your listener? I am guessing that the NPE comes from the fact that the listener uses an ImageFetcher instance that is null. When dereferencing it a NullPointerException is thrown.

This is not happening when you change to a static method since there is no instance involved.

smink
Cheers for the comment, I added the code and realised when I was adding it that I have removed the initiator from the constructor in the main app class... :( I feel daft.
Emdiesse
Happens to we all doesn't it ;)
smink
+1  A: 

If you get NullPointerException on anImg.getImage(), then it simply means that anImg is null. Do a System.out.println(anImg);, you'll see that it prints null.

To fix it, you need to instantiate anImg somehow. E.g.

ImageFetcher anImg = new ImageFetcher();

Only then you'll be able to access it and call methods on it.

BalusC
Thanks very much, I knew it was something simple, I realised when I was adding the extra code for smink that I hadn;t initiated the object. I feel daft... but we all do it don't we. Please confirm I am not the only one :)What a waste of the day!!!
Emdiesse
@Emdiesse on stackoverflow it is customary to mark the answer that solved your problem as accepted (using the tick below the vote counter)
Bozho
Cheers :) I thought there would be something like that somewhere but I couldn't find it.
Emdiesse