我的BaseApplication可以说看起来像
public class ApplicationBase extends Application {
String someKey;
public String getSomeKey() {
return someKey;
}
public void setSomeKey(String someKey) {
this.someKey = someKey;
}
}
我有一个片段它执行一些操作并在
的基础上决定String key = (ApplicationBase) getActivity().getApplication()).getSomeKey();
if(key.equals(anotherString){
Do Some thing
...
}else{
Do Some thing
....
}
运行顺利,但有时(罕见情况)它会因此错误而崩溃
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.Application android.support.v4.app.FragmentActivity.getApplication()' on a null object reference
如何解决? (我尽力保持这个问题的普遍性不是个人的,以便另一个程序员将这个问题与他的问题联系起来所以请不要贬低:p)
或者我可以这样做以防止此错误吗?
if((ApplicationBase) getActivity().getApplication() !=null){
String key = (ApplicationBase) getActivity().getApplication()).getSomeKey();
if(key.equals(anotherString){
Do Some thing
...
}else{
Do Some thing
....
}
}
答案 0 :(得分:2)
您的片段尚未附加到您的活动或已被销毁。尝试在onAttach()
方法
答案 1 :(得分:1)
正如@shmakova已指出的那样,在片段附加到活动之前,您无法获取片段的活动主机。因此,您需要在onAttach()
内或调用onAttach()
之后获取活动。您也可以使用标志,如下所示:
public class YourFragment extends Fragment {
private boolean mIsAttached = false;
...
protected void onAttach() {
mIsAttached = true;
}
private void doSomething() {
if(mIsAttached) {
// I am attached. do the work!
}
}
}
旁注:
如果您依赖于Application类,可以直接使用Application类,将Application类设为singleton(尽管Application已经是singleton),如下所示:
public class YourApplication extends Application {
private static YourApplication sInstance;
private String someKey;
public static YourApplication getInstance() {
return sInstance;
}
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
}
public String getSomeKey() {
return someKey;
}
public void setSomeKey(String someKey) {
this.someKey = someKey;
}
}
然后你可以用以下方法调用方法:
String key = YourApplication.getInstance().getSomeKey();