我有一个名为SharedData.java的getter setter类。当我要在代码中隐式暗示它时,我得到了空指针异常。这是SharedData类:

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;
}

}

这是我的代码:
       SharedData sharedData ;
       sharedData = SharedData.getInstance();
       sharedData.setSrc_latitude(latitude);
   sharedData.setEnd_longitude(longitude);

有人可以帮我吗?谢谢 。

最佳答案

您从未初始化过sharedData,因此其值为null,对其调用方法会使程序崩溃。

我认为您正在尝试使用Singleton Pattern。请尝试以下方法:

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;
}

10-06 13:57