java中getter setter的空指针异常

时间:2012-09-12 17:24:25

标签: java android getter-setter

我有一个名为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);

有人可以帮帮我吗?谢谢。

5 个答案:

答案 0 :(得分:6)

从不初始化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;
}

答案 1 :(得分:3)

SharedData.getInstance();

返回null。后来你试图在它上面调用一个方法:

sharedData.setSrc_latitude(latitude);

对象的引用仍然是null

答案 2 :(得分:2)

您没有实例化该类,因此getInstance()会返回null

在课程开始时,请替换:

private static SharedData instance = null;

by:

private static SharedData instance =  new SharedData() ; // creates a new instance

答案 3 :(得分:1)

即使使用singleton pattern,您也应该至少将对象SharedData实例化一次。

试试这个

SharedData sharedData = new SharedData();  
       sharedData = SharedData.getInstance();
       sharedData.setSrc_latitude(latitude);
   sharedData.setEnd_longitude(longitude);

答案 4 :(得分:1)

更改private static SharedData instance = null;

private static SharedData instance = this;

让你的班级静止

public static class SharedData {

另外,让getter setters静态..