I’m getting a null pointer exception despite initialising all of my objects correctly (to my knowledge). Baiscially, I need someone to point out where I’ve been an idiot.
The runtime NPE occurs here:
public class CDAlbum implements Album{
private String title;
private String genre;
private String artist;
private ArrayList<String> tracks;
private int i=0;
public CDAlbum() { //constuctor
title = "Unknown CD";
genre = "Unknown genre";
artist = "Unknown artist";
ArrayList<String> tracks = new ArrayList<String>(); //NPE occurs on this line
tracks.add("-- no tracks --");
}
//snip
And the code calling the constructor:
CDAlbum tempCD;
tempCD = new CDAlbum();
I think I’m initialising everything properly, so I can’t see where this null pointer exception is coming from. A little help?
As it turns out, your problem was because you had forgotten to recompile your code! After downloading the code from your dropbox, I decompiled
CDAlbumto reveal an outdated constructor:After recompiling (after following my suggestions), the code appeared to work fine.
As I stated in my comments, your code here is probably modified and not the actual code producing the exception; you’re more than likely trying to add to the
tracksfield, however you never initialized it — you only initialized the local variabletracks.Try doing something like the following…
You should post an SSCCE or at least the unmodified code to receive accurate help. It’s going to be tough to solve the issue if you treat it as a black box.
Note you can move all of your initialization to the field declarations, e.g.