2

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?
Ove Stoerholt
  • 3,843
  • 4
  • 25
  • 33
  • 1
    What is the specific Lint warning? That `getActivity()` might return a `null` value? – CommonsWare Nov 06 '17 at 14:09
  • Possible duplicate of [How to pass values from Fragment to Activity](https://stackoverflow.com/questions/41427759/how-to-pass-values-from-fragment-to-activity) – Pavneet_Singh Nov 06 '17 at 14:13
  • use the suggested approach , so instead sending data , let that overridden function inflate the menu – Pavneet_Singh Nov 06 '17 at 14:17
  • @Pavneet_Singh I think you have misunderstood my question. I am asking why getActivity() suddenly starts to give me lint warnings. – Ove Stoerholt Nov 06 '17 at 14:21
  • 1
    [Read this](https://stackoverflow.com/questions/29786011/how-to-fix-getactionbar-method-may-produce-java-lang-nullpointerexception) – Pavneet_Singh Nov 06 '17 at 14:59

1 Answers1

5

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.

Niklas
  • 23,674
  • 33
  • 131
  • 170
  • Yes. I know that he did, and also thought that might have been the reason. But where in the documentation does it say that the activity can be null? – Ove Stoerholt Nov 09 '17 at 07:02
  • If the fragment is not attached to the activity or detached you'll get null from the call. – Niklas Nov 09 '17 at 15:16
  • 4
    This answer seems to address part (2) of the OP's question (the why), but not (1) (what we're supposed to practically do about it). – Trevor Dec 27 '17 at 15:32
  • It's his decision. Either work without the Activity or throw an exception. – Niklas Dec 28 '17 at 16:52