这个nullpointer怎么可能发生?

时间:2017-11-28 10:06:28

标签: android android-layout android-fragments

我有一个标签式应用程序,片段作为标签。该应用程序大约5岁。

这与我长期以来的代码相同,但在最近几周,我在 Google控制台崩溃日志中突然出现了几个 nullpointers

我看不出这段代码怎么可能导致 nullpointer ,所以我希望有人可以看到我不能的东西。

    private TextView switchSpace;

@Override
public void onActivityCreated(Bundle savedState) {
    super.onActivityCreated(savedState);
    initGUIComponents();        
    checkSpace();
}

private void initGUIComponents() {
    switchSpace = getView().findViewById(R.id.rightText);        
}

private void checkSpace() {
    if (shouldShowComponent) {
        switchSpace.setText(textToShow);
        switchSpace.setVisibility(View.VISIBLE);
    } else {
        switchSpace.setVisibility(View.GONE);//NULLPOINTER IN CONSOLE!!
    }
}

堆栈跟踪显示在onActivityCreated中调用checkSpace会导致 nullpointer 。再一次,它一直有效,我总共只有3次崩溃,但仍然如此。怎么会发生这种情况?

指针非常感谢。

编辑,堆栈跟踪:

  

at x.y.z.tabs.MainFragment.checkSpace(MainFragment.java:268)     at x.y.z.tabs.MainFragment.onActivityCreated(MainFragment.java:81)     在android.support.v4.app.Fragment.performActivityCreated(Fragment.java:2363)     在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1442)     在android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1740)     在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1809)     在android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)     在android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2580)     在android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:2367)     在android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:2

3 个答案:

答案 0 :(得分:0)

  • shouldShowComponent已初始化?
  • 在致电TextView时,您是否错过了setText(textToShow)的演员?
  • 您确定getView().findViewById(R.id.rightText);会返回正确的视图(如果有的话)吗?

答案 1 :(得分:0)

制作一个像这样的视图对象:

 private TextView switchSpace;
 private View view;

在片段的Oncreateview中初始化文本视图

       //in on create view


        // initialize view
       view=inflater.inflate(R.layout.yourfragment, container, false);

        //find text view  
       switchSpace = (TextView)view.findViewById(R.id.rightText); 

       return view;

然后在On activity中创建了什么

          @Override
          public void onActivityCreated(Bundle savedState) {
          super.onActivityCreated(savedState);

          checkSpace();
          }

答案 2 :(得分:0)

您正在使用getView()将视图与其ID相关联。根据{{​​1}}生命周期的文档,可以在Fragment夸大之前调用getView(),当发生这种情况时,View实际上是getView()因此null {1}}无法将您的getView()与ID和TextView TextView相关联。当应用尝试在视图上执行null的操作时,exception会抛出。因此,只需使用虚增nullTextView与其OnCreatView内的ID相关联即可。这是我的意见,我可能错了,但这可以解释为什么View总是反而有时(在视图实际膨胀之前调用exception时)

相关问题