在空对象引用Error上获取'getActivity()。getApplication()'

问题描述 投票:0回答:2

我有我的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
         ....
     }
 }
java android android-fragments fragment android-context
2个回答
2
投票

您的片段尚未附加到您的活动或已经被销毁。尝试在onAttach()方法中获取密钥


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已经是单例)直接使用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();
© www.soinside.com 2019 - 2024. All rights reserved.