Null pointer exception of getter setter in Java
•
Java
I have one named shareddata Getter setter class of Java When I want to hint at it on my code, I get a null pointer exception This is the shareddata class:
public class SharedData { private static SharedData instance = null; public SharedData() { // randomizeServers(); } // data to be shared private double src_latitude = -1; private double src_longitude = -1; private double end_latitude = -1; private double end_longitude = -1; //Getter-Setters public static SharedData getInstance() { return instance; } public static void setInstance(SharedData instance) { SharedData.instance = instance; } public double getSrc_latitude() { return src_latitude; } public void setSrc_latitude(double src_latitude) { this.src_latitude = src_latitude; } public double getSrc_longitude() { return src_longitude; } public void setSrc_longitude(double src_longitude) { this.src_longitude = src_longitude; } public double getEnd_latitude() { return end_latitude; } public void setEnd_latitude(double end_latitude) { this.end_latitude = end_latitude; } public double getEnd_longitude() { return end_longitude; } public void setEnd_longitude(double end_longitude) { this.end_longitude = end_longitude; } }@H_502_12@这是我的代码:
SharedData sharedData ; sharedData = SharedData.getInstance(); sharedData.setSrc_latitude(latitude); sharedData.setEnd_longitude(longitude);@H_502_12@有人可以帮帮我吗?谢谢 .
Solution
You never initialize shareddata, so its value is null. Calling a method on it will crash your program
I think you tried to use singleton pattern Try the following
Try this
private static SharedData instance = new SharedData(); \\ Initialize here private SharedData() { // Make it private.... // randomizeServers(); } // data to be shared private double src_latitude = -1; private double src_longitude = -1; private double end_latitude = -1; private double end_longitude = -1; //Getter-Setters public static SharedData getInstance() { return instance; }@H_502_12@
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码