I'm still puzzled by the fact, that Google puts a method in the Android API that sometimes works and sometimes not; namely Fragment.getActivity()
. I know, I can check if the result is null
and there is also the isAdded()
method. However, how should I proceed when these checks have a negative result? When I've come this far, there is a reason I want to access the Activity
, like accessing Resources
or Preferences
or do one of the zillion things that require a Context
in Android.
I could simply not do whatever I was about to do. However, I think it would be a poor user experience, if my App sometimes executes the action the user selected and sometimes not. In fact, I think letting my App just crash wouldn't be much worse.
Or I could tell the user about the detached activity and that he should try again later. But wait, Toast
requires a Context
, so I can't even do that.
Or should I just wait for the Activity to be reattached like this?
Activity activity = getActivity();
while (activity == null) {
Thread.sleep(10);
activity = getActivity();
}
(I'm not seriously suggesting this, I merely want to illustrate how desperate I am)
Maybe I'm thinking about this all wrong. Maybe I'm trying to do things the wrong way. Maybe there is a school of thought about how to use Fragments that I haven't heard of. However, if I should avoid to access the Activity
in a Fragment
, why is the getActivity()
method there in the first place?
The particular problem I'm struggling with right now is that in a PreferenceFragment
in an OnSharedPreferenceChangeListener
I want to give the user a Toast
message:
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
That works most of the time, but it sometimes crashes because getActivity()
returned null
.