【问题标题】:Getting 'getActivity().getApplication()' on a null object reference Error在空对象引用上获取“getActivity().getApplication()”错误
【发布时间】:2018-08-11 21:07:08
【问题描述】:

我有我的 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
         ....
     }
 }

【问题讨论】:

  • 您可以通过在 try catch 块中使用代码 FragmentActivity.getApplication 来避免该错误。
  • 我可以知道为什么会出现这个错误吗?
  • 因为调用该方法时,有时上下文还没有被初始化,如果上下文没有被初始化而你使用了上下文,就会出现空点错误。
  • getActivity() 可以在两种情况下返回 null 。您的片段尚未附加到 Activity 并且您的片段被销毁。
  • 那么我应该按照我在粗体文本后写的内容做吗?

标签: java android android-fragments fragment android-context


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    正如@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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-29
      • 2021-08-16
      • 2021-08-04
      • 1970-01-01
      • 2022-01-15
      • 2016-01-14
      • 2015-03-08
      相关资源
      最近更新 更多