[英]Getting null object reference when using getactivity() or getcontext() from fragment to adapter
[英]Getting 'getActivity().getApplication()' on a null object reference Error
我有我的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
怎么解決? (我盡力使這個問題變得通用而不是私人的,以便另一個編碼員將此問題與他的問題聯系在一起,所以請不要downvote:p)
還是可以這樣做以防止出現此錯誤?
if((ApplicationBase) getActivity().getApplication() !=null){
String key = (ApplicationBase) getActivity().getApplication()).getSomeKey();
if(key.equals(anotherString){
Do Some thing
...
}else{
Do Some thing
....
}
}
您的片段尚未附加到您的活動中或已被銷毀。 嘗試在onAttach()
方法中獲取密鑰
正如@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已經是單例)來直接使用Application類,如下所示:
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.