我在库中使用了singleton来保存数据,但有时发现当用户获得singleton的变量时,用户返回了null。还有其他方法吗?
我目前使用的是singleton模式。
public class Factory {
private static Factory sInstance = null;
private final Config mConfig;
public Factory(Config config) {
mConfig = config;
}
public static Factory getInstance() {
return sInstance;
}
}
线路上的一些用户发现以下调用将返回null。
Factory.getInstance().mConfig
您可以扩展基本android.app.Application类并添加成员变量,如:
public class MyApplication extends Application {
private String someVariable;
public String getSomeVariable() {
return someVariable;
}
public void setSomeVariable(String someVariable) {
this.someVariable = someVariable;
}
}
在你的android清单中,你必须声明实现android.app.Application的类(将android:name=".MyApplication"
属性添加到现有的应用程序标签中(:
<application
android:name=".MyApplication"
android:icon="@drawable/icon"
android:label="@string/app_name">
然后在你的活动中,你可以获得并设置变量,如下所示:
// set
((MyApplication) this.getApplication()).setSomeVariable("foo");
// get
String s = ((MyApplication) this.getApplication()).getSomeVariable();