We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I have some code I'm writing just now, in which I load a 2d array of images and then display them in a grid. The images are titled "tile.x.y.png" with x and y representing the location in the grid for each image. ("tile.-7.4.png" for example).
I want to load every image in the folder onto this grid, but some of those images don't exist, lets say my grid of images is 10 images tall and wide, but image -5,3 doesn't exist. When the code tries to load that image, is it possible to have it ignore the NullPointerException and move on? Or is there some kind of "if(noFile) " thing I can do?
Here's some more in depth information, if it helps. During setup, an object is created for every tile in a grid of my chosen size, using:
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
NodeList[i][j] = new Node(i,j,"tile." + i + "." + j + ".png");
}//for j
}//for i
Each object is given two variables, its x and y position, through i and j. The constructor then uses that to load the image with those co-ordinates:
Node(int x_, int y_){
x = x_;
y = y_;
img = loadImage("tile." + x + "." + y + ".png");
}//construct
I hope this is enough information to help, and thanks in advance.
Answers
Hi Bazul - here is a paragraph from the loadImage() description:
If the file is not available or an error occurs, null will be returned and an error message will be printed to the console. The error message does not halt the program, however the null value may cause a NullPointerException if your code does not check whether the value returned is null.
So, I'm guessing just a check there and skip to the next [i] [j]?
doesn't match your constructor's signature:
anyway,
loadImage() itself won't throw a NPE (at least not in version 1.5.1), it'll return a null. it's when you try to use the image that failed to load that you'll get the NPE.
Function loadImage() doesn't halt Processing programs! [-X
What you can do checking for
null
before using image() to display any PImage!Thanks for the information, I wasn't aware that the null check existed. All sorted!