0

I have this method:

private ArrayList<Image> imageArray(File files[]) {

    ArrayList<Image> images = null;

    for(int x = 0; files.length > x; x++) {

        //I want to add each PNG-File to the Image-Array

        try {
            images.add(x, ImageIO.read(files[x])); //Demo.imageArray(Demo.java:23)
        }catch(IOException | ArrayIndexOutOfBoundsException exception) {
            exception.printStackTrace();
        }

        //Now I scale each Image, so it fits the screenSize

        int newWidth = (int) screenSize.getWidth(),
            newHeight = newWidth * images.get(x).getHeight(null) / images.get(x).getWidth(null);

        if(newHeight > screenSize.getHeight()) {

            newHeight = (int) screenSize.getHeight();
            newWidth = newHeight * images.get(x).getWidth(null) / images.get(x).getHeight(null);
        }

        images.set(x, images.get(x).getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH));
    }

    return images;
}

which causes this Exception :

Exception in thread "main" java.lang.NullPointerException
    at Demo.imageArray(Demo.java:23) //I've marked the position in the code!
    at Demo.main(Demo.java:47) // Just, when I want to use the method anywhere

Why do I get that Error and how can I work around it? I have added a parameter, when I wanted to use the method, which looks like this :

imageArray(new File[] {new File("filePath to PNG-Image"),
            new File("filePath to PNG-Image")})
Jongware
  • 22,200
  • 8
  • 54
  • 100

1 Answers1

1

A simple solution would be to initialize images.

So instead of just doing this:

ArrayList<Image> images = null;

Do this:

ArrayList<Image> images = new ArrayList<>();
Francis Bartkowiak
  • 1,374
  • 2
  • 11
  • 28