以下是我的活动代码。我致电setKey()
来设置密钥,但当我使用getKey()
时,它会返回""
;
public class SharedData {
// This is a singleton class that provides a global data
private SharedData instance = null;
private SharedData() {
}
// Data to be shared
private String key = "";
public static SharedData getInstance() {
instance = new SharedData();
return instance;
}
public String getKey() {
return key;
}
public void setKey(String skey) {
key = skey;
}
}
答案 0 :(得分:2)
似乎每次都是每次为SharedData创建新实例
public class SharedData {
// this is a singleton class that provides a global data
private static SharedData instance = null;
private SharedData() {
}
// data to be shared
private String key = "";
public static SharedData getInstance() {
if (null == instance) {
instance = new SharedData();
}
return instance;
}
public String getKey() {
return key;
}
public void setKey(String skey) {
key = skey;
}
}
现在你需要在每行下面的行中使用相同的实例:
SharedData data = SharedData.getInstance();
data.setKey("some string");//to set value
data.getKey(); //to get value