findViewById() may produce NullPointerException

后端 未结 3 1952
灰色年华
灰色年华 2021-01-12 03:42

I have many of these calls:

(ListView) getView().findViewById(R.id.main_list_view);
(TextView) getView().findViewById(R.id.items_no);
....

相关标签:
3条回答
  • 2021-01-12 04:30

    You should ignore the problem;

    As @DanDar3 wrote -> getView() can return null and AndroidStudio highlights that.

    But if you really want to make AndroidStudio happy - sure you can...:
    Just assert view is not null:

    View view = getView();
    assert view != null;
    (ListView) view.findViewById(R.id.main_list_view);
    (TextView) view.findViewById(R.id.items_no);
    
    0 讨论(0)
  • 2021-01-12 04:30

    That is cause getView() may return null and is annotated as @Nullable, check out the sources and its JavaDoc - CTRL+Click on getView() call in your code.

    /**
     * Get the root view for the fragment's layout (the one returned by {@link #onCreateView}),
     * if provided.
     * 
     * @return The fragment's root view, or null if it has no layout.
     */
    @Nullable
    public View getView() {
        return mView;
    }
    

    You can wrap your code yourself and check for null to have the warning go away, or otherwise place the cursor anywhere inside findViewById() call, wait couple of seconds for the lightbulb to show up (or press Alt+Enter) and then choose one of the suggested solutions.

    0 讨论(0)
  • 2021-01-12 04:38

    This is a known issue in android.support.v7.app.AppCompatActivity and it has been fixed in v24.

    https://code.google.com/p/android/issues/detail?id=203345

    You won't have any issues with android.support.v4.app.FragmentActivity or android.app.Activity

    0 讨论(0)
提交回复
热议问题