Detecting if a final is blank in a constructor - java

I'm trying to create an enum for final Images, where the variable 'image' would be loaded from a file. If an IOException occurs, I want 'image' to be set to null. However, according to the compiler, 'image' may or may not be set when the catch block runs.
public enum Tile {
GROUND("ground.png"), WALL("wall.png");
final Image image;
Tile(String filename) {
try {
image = ImageIO.read(new File("assets/game/tiles/" + filename));
} catch (IOException io) {
io.printStackTrace();
image= null; // compiler error 'image may already have been assigned'
}
}
}
Final variables need to be set in the constructor, so if the image for some reason cannot be read, it has to be set to something. However, there's no way to tell whether or not image has actually been set. (In this case, the catch block only will run if no image is set, but the compiler says that it may have been set)
Is there a way for me to assign image to null in the catch block only if it hasn't been set?

Try using a local temporary variable:
public enum Tile {
GROUND("ground.png"), WALL("wall.png");
final Image image;
Tile(String filename) {
Image tempImage;
try {
tempImage= ImageIO.read(new File("assets/game/tiles/" + filename));
} catch (IOException io) {
io.printStackTrace();
tempImage= null; // compiler should be happy now.
}
image = tempImage;
}
}

Here is the solution I ended up using. It adds a method so that the code return if the ImageIO class does find an image, leaving no chance for the catch statement to be called.
public enum Tile {
GROUND("ground.png"), WALL("wall.png");
final Image image;
Tile(String filename) {
image = getImage(filename);
}
Image getImage(String filename) {
try {
return ImageIO.read(new File("assets/game/tiles/" + filename));
} catch (IOException io) {
io.printStackTrace();
return null;
}
}
}
However, this isn't really a way to detect a blank final variable. I'm hoping to see if there's a way to set a final variable inside a try/catch without going around the issue using temporary variables.

Related

Dynamically get image paths in eclipse

this is my code below
public BufferedImage icon32 = loadBufferedImage("/icon/icon32.png");
public BufferedImage icon64 = loadBufferedImage("/icon/icon64.png");
private BufferedImage loadBufferedImage(String string)
{
try
{
BufferedImage bi = ImageIO.read(this.getClass().getResource(string));
return bi;
} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
I just wanted to know if there's a way to dynamically get the images from my image directory in eclipse instead of having to access them one by one

Loading a BufferedImage in a .jar

I'm currently trying working on an own game and created a Animation class, my problem is that i want the programm to be able to still find all the images when i create a jar out of it so I tried to load an Image via
BufferedImage img = ImageIO.read(getClass().getClassLoader().getResourceAsStream("player.png"));
but when I start the code I get a NullPointerException, i checked the location twice but the image exists and there should be no problems, can anyone help me out a bit?
try this
public BufferedImage loadImage(String fileName){
BufferedImage buff = null;
try {
buff = ImageIO.read(getClass().getResourceAsStream(fileName));
} catch (IOException e) {
e.printStackTrace();
return null;
}
return buff;
}

What's the source of this NullPointerException

OK, so I'm writing an Android app, and am trying to download a Bitmap and set it as an ImageView. The code is below for the relevant parts:
private class GetContactInfo extends AsyncTask<String, Void, ContactInfo[]> {
#Override
protected ContactInfo[] doInBackground(String... url) {
// Instantiate what is needed
URL json = null;
//Set the JSON URL
try {
json = new URL(url[0]);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
// Use Jackson library to read out the data from the contacts page
try {
contacts = mapper.readValue(json, ContactInfo[].class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Add everything into the bitmap ArrayList
for (int i = 0; i < contacts.length; i++) {
String imageURL = contacts[i].getSmallImageURL();
// Download the Bitmap and add it to the ArrayList
try {
bitmap.add(downloadBitmap(imageURL));
} catch (IOException e) {
e.printStackTrace();
}
}
// Return statement
return contacts;
}
public Bitmap downloadBitmap(String imageURL) throws IOException {
URL url = new URL(imageURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream stream = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(stream);
if (bitmap == null) {
Log.e("Null", "Bitmap null");
}
return bitmap;
}
The log never catches that bitmap is null, or at least it doesn't show it (I see in the stack trace that there are 4 more errors, but they never show up and I'm not sure how to expand it to show the other errors.)
The NullPointerException comes at the bitmap.add(downloadBitmap(imageURL)); line. So somehow my downloadBitmap function is returning a null result. Any ideas?
Edit: I'm not sure if this matters, but the images in the URLs are .jpeg files.
Edit 2: Put this in the comments so I will edit it into my post as well, bitmap is declared as a Global Variable like so ArrayList<Bitmap> bitmap; This is so I can later use it in my onPostExecute method.
As you said the error is at line
bitmap.add(downloadBitmap(imageURL));
which means culprit is your bitmap variable and not downloadBitmap(imageURL) method.
Also, in your edit you have mentioned that you have declared bitmap as a global variable - ArrayList bitmap;
In order to access(add bitmap onjects to it) this globally declared variable you must initialize it.
In your onCreate do -
bitmap = new ArrayList<Bitmap>();
and the NPE must go.
While you are downloading images from the Internet, you should use an async request. In downloadBitmap the connection is downloading in another thread, but the main thread has returned bitmap immediately, whether or not the downloading is accomplished.
Where did you initialized bitmap? As far as I can tell, it is null and you are using that null object, so Null Pointer Exception come out. That's from the information you provided. If the error is occurred inside the function, it's the different matter.

How to properly extract simple try/catch blocks that load resources in java?

Currently there is a method that loads an image from an URL and then processes it like follows:
BufferedImage tempImage;
try {
tempImage = ImageIO.read(url);
}
catch (IOException e) {
return;
}
final BufferedImage image = tempImage;
To clean the code up a bit, I would like to extract the try/catch block while preserving the functionality of exiting the method if the loading of the image fails. I have tried extracting the block as follows:
final BufferedImage image = loadImageFromURL();
if (image == null)
return;
//--------------------------------------
private BufferedImage loadImageFromURL() {
BufferedImage tempImage = null;
try {
tempImage = ImageIO.read(url);
}
catch (IOException e) {
LogUtils.severe(e);
}
return tempImage;
}
The problem is that if the loading of the image fails, the method returns null, which does not make the code any cleaner, as I have to perform an additional null check. I have read through Clean Code: A Handbook of Agile Software Craftsmanship but all the examples seem to rethrow the exception in some form: is that the only/correct way to go?
We don't know the complete situation you are in, but I would just add a throw clause to the method signature and do not use any try catch.
private BufferedImage loadImageFromURL() throws IOException
{
return ImageIO.read(url);
}
Which basically resolves back to the original method, without extracting the try-catch. If the loading fails, the method will stop, but not really return. The exception will go all the way back to some piece of code that handles it properly.

Java - How to access an image packed in an applet jar

I have created an applet jar. That jar contains an images in the following folder
com\common\images\red.bmp
Now, I want to display this image on the Swing Applet.
private static final ImageIcon redIndicator = new ImageIcon("com\\common\\images\\red.bmp");
After that, I have attached the redIndicator to a JPanel but I am not able to see this image.
Any suggestions?
==================================EDITED=========================================
private static final ImageIcon marker = loadImage("com/common/images/scale.jpg");
#SuppressWarnings("unused")
private static ImageIcon loadImage(String imagePath) {
BufferedInputStream imgStream = new BufferedInputStream(TpcHandler.class.getResourceAsStream(imagePath));
int count = 0;
if (imgStream != null) {
byte buf[] = new byte[2400];
try {
count = imgStream.read(buf);
} catch (java.io.IOException ioe) {
return null;
} finally {
if (imgStream != null)
try {
imgStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (count <= 0) {
LOGGER.warning("Empty image file: " + imagePath);
return null;
}
return new ImageIcon(Toolkit.getDefaultToolkit().createImage(buf));
} else {
LOGGER.warning("Couldn't find image file: " + imagePath);
return null;
}
}
I am getting the following exception
java.io.IOException: Stream closed
at line count = imgStream.read(buf);
This should do the trick (if called from a class loaded from that same jar):
new ImageIcon(getClass().getResource("/com/common/images/red.bmp"))
Use YourPanel.class.getResourceAsStream("/com/common/images/red.bmp"), read the stream to a byte[] and construct the ImageIcon based on that. (and don't use bmps - prefer png or jpeg)
Applets and Images that is a frequently asked questions so, as for Java applets and images, I recommend you read one of my previous answers hope it helps a bit :)
Good luck

Categories