Search code examples
javaandroidcodenameoneinputstream

Codename One: Resources Not Being Found in Android Build


I am using Codename One to build a little game. My game works in the simulator, however, whenever I run an Android build of the game, I'm met with

java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.BufferedReader.close()' on a null object reference

I used an if statement to simply close an input stream if it is not null but then nothing loads in, which seems to me I am not configuring my resources correctly.

This is how I am loading in my image resources:

public static final String DUCKY_ATLAS = "/duckySprite.png";
public static final String LEVEL_ATLAS = "/mapSprite.png";

public static final String START_LEVEL = "/levelOne.png";
public static final String OBSTACLE_SEQUENCES = "/levelSequences.png";

//method to pull Image from file 
public static Image getSpriteAtlas(String file) {
    Image img = null;
    try {
        InputStream is = CN.getResourceAsStream(file);
        img = Image.createImage(is);
        is.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return img;
}

The location of my resources folder looks like : /common/src/main/resources

There is also no nesting within it.

Any help would be greatly appreciated.


Solution

  • Check that the files in the folder match the case you use as even the file names are case sensitive. I suggest showing the specific file name that wasn't found as an error so you'll know which file is missing.

    Other than that you should use the newer syntax of try-with-resources as part of Java 8:

    try(InputStream is = CN.getResourceAsStream(file)) {
        img = Image.createImage(is);
    } catch (IOException e) {
        Log.e(e);
        Dialog.show("Error", "Loading file failed: " + file, "OK", null);
    }
    return img;
    

    This removes the need to close. Also, always use Log.e() instead of printStackTrace.