对 Singleton 对象的空引用
null reference to a Singleton object
我正在尝试创建一个全局变量,可以从任何地方访问它,包括 Activity、片段和其他自定义 classes。
public class Global extends Application {
private static Global sInstance;
private String mSharedInfoFileName; //can be any custom object
public static Global getInstance() { return sInstance; }
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
initialize();
}
private void initialize() { mSharedInfoFileName = "globalInfo"; }
public String getFileName() { return mSharedInfoFileName; }
private Global() { }
}
并尝试像这样使用它
public class MyFragment extends android.support.v4.app.Fragment {
String s = Global.getInstance().getFileName();
}
即使在 class 范围内声明它仍然给出相同的错误
private static Global mGlobal = Global.getInstance();
这让我在空对象引用上尝试开票...Global.getFileName()'。我错过了什么?
谢谢
将此方法更改为静态方法:
public static String getFileName() {
return mSharedInfoFileName;
}
并像下面这样称呼它:
Global.getFileName();
mSharedInfoFileName 变量也必须是静态的:
private static String mSharedInfoFileName;
我正在尝试创建一个全局变量,可以从任何地方访问它,包括 Activity、片段和其他自定义 classes。
public class Global extends Application {
private static Global sInstance;
private String mSharedInfoFileName; //can be any custom object
public static Global getInstance() { return sInstance; }
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
initialize();
}
private void initialize() { mSharedInfoFileName = "globalInfo"; }
public String getFileName() { return mSharedInfoFileName; }
private Global() { }
}
并尝试像这样使用它
public class MyFragment extends android.support.v4.app.Fragment {
String s = Global.getInstance().getFileName();
}
即使在 class 范围内声明它仍然给出相同的错误
private static Global mGlobal = Global.getInstance();
这让我在空对象引用上尝试开票...Global.getFileName()'。我错过了什么?
谢谢
将此方法更改为静态方法:
public static String getFileName() {
return mSharedInfoFileName;
}
并像下面这样称呼它:
Global.getFileName();
mSharedInfoFileName 变量也必须是静态的:
private static String mSharedInfoFileName;