So I had a question on here the other day about how to accessing the same data class with two different other classes without creating separate instances. It was recommended to use a singleton so i have done some research but there isn’t a lot about it.
The issue I’m having is that my main class gets a null pointer exception when trying to access the data singleton. But my other class can access it and get the data just fine. How exactly is that possible? I have a pretty basic setup…
singleton
public enum laneData {
INSTANCE;
private String laneID;
public String getLaneID() {
return laneID;
}
public void setLaneID(String laneID) {
this.laneID = laneID;
}
}
main class call
private laneData laneData;
public void init() {
laneData.setLaneID("test"); //these two lines each throw null pointer unless commented out
System.out.println(laneData.getLaneID());
....
other class
public class XMLParser {
private LaneGUI laneGUI;
private laneData laneData;
public void parseInputString(String input){
laneData.setLaneID(getCharacterDataFromElement(line)); //both of these work fine
System.out.println("stored ID: " + laneData.getLaneID());
You need
private laneData laneData = laneData.INSTANCE;.You can also just use
laneData.INSTANCE.getLaneID().Java guidelines also recommend than Class and Enum names be capitalized, I.E.
LaneData.