Android Studio 3.0 lint warnings for references to activity

走远了吗. 提交于 2019-12-11 00:55:16

问题


After upgrading my project to use Android Studio 3.0 with API level 27.0.0 (Android 8.1) I get a lot of new lint warnings related to using getActivity() inside a fragment (which I thought was perfectly all right).

Examples:

((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);

getActivity().getMenuInflater().inflate(R.menu.pavingreport_dialog_menu, menu);

Both examples complains about null exceptions.

Example:

Method invocation 'getMenuInflater' may produce 'java.lang.NullPointerException'

I know I can fix this by adding activity as a field and initialize it during onCreate or something, but this only removes the warning...

Questions:

  1. Is referring to the Activity using getActivity not the way to go? What is best practice?
  2. Is this a 'bug' in AS that I can ignore?

回答1:


getActivity() in Fragment got the @Nullable annotation with support libraries 27.0.0. Thanks to Jake. Meaning this is now working as expected since it can return null.



来源:https://stackoverflow.com/questions/47138807/android-studio-3-0-lint-warnings-for-references-to-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!