1

I'm new to fragments and I'm trying to take an activity and convert it to a fragment. A lot of the stuff I'm using needs Context and when I use getActivity() I get a log of warnings that it may return null and I'm not sure how to fix it. I read that I should attach the fragment to the activity somehow, but I'm not sure. I'm basically using one activity and going to have 4 fragments because I want to use a navigation drawer.

This is in the main activity for showing the fragments

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
        case R.id.nav_calendar:
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new CalendarFragment()).commit();
            break;
        case R.id.nav_survey:
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new SurveyFragment()).commit();
            break;
        case R.id.nav_forum:
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ForumFragment()).commit();
            break;
        case R.id.nav_logout:
            logout();
            break;
        case R.id.nav_contact:
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ContactFragment()).commit();
            break;
    }

    drawer.closeDrawer(GravityCompat.START);
    return true;
}

And in the fragments onCreateView() I have this, I have a lot of methods and most of them use Context, I added the if statement because of the same warning and that seemed to work there but how should I take care of the rest on Context uses. I don't see making an if statement for each time a good thing.

View view = inflater.inflate(R.layout.fragment_calendar, container, false);

if (getActivity() != null) {
    ((MainActivity) getActivity()).getSupportActionBar().setTitle(R.string.calendar);
}

AndroidThreeTen.init(getActivity());
initialBuild(view);
buildCalendarView();
setRecyclerView();


return view;

Edit

Related images

Also I tried without the @NonNull enter image description here

enter image description here

Nancy
  • 1,021
  • 4
  • 23
  • 45

1 Answers1

1

See https://www.reddit.com/r/androiddev/comments/aklpz4/why_does_getactivity_in_fragment_might_be_null/.

You can use onActivityCreated() to access getActivity(), it won't be null. I usually use onCreate() or onCreateView() to get getActivity(), but in some rare cases a fragment's view can be created before hosting activity when an application starts (but I don't remember this in real work).

In any case getActivity() is marked as Nullable, so you can compare it with null in any case.

UPDATE 1

See getActivity() returns null in Fragment function.

Between onAttach() and onDetach() you can get getActivity(), so save context in onAttach() and later use it in onCreateView().

UPDATE 2

Fragment:

private Activity activity;

@Override
public void onAttach(Context context) {
    super.onAttach(activity);
    if (context instanceof Activity){
        activity = (Activity) context;
    }
}

@Override
public void onDetach() {
    super.onDetach();
    activity = null;
}

@Override
public void onCreateView() {
    // Use activity here.
}

UPDATE 3

Sorry,

@Override
public void onAttach(@NonNull Context context) {
    super.onAttach(context);
    if (context instanceof Activity){
        activity = (Activity) context;
    }
}
CoolMind
  • 26,736
  • 15
  • 188
  • 224
  • I read about the `onAtttach()` but I don't know where that is supposed to go? or how to set that up – Nancy Apr 15 '20 at 17:36
  • I get an error on `onAttach` saying overriding method should call super – Nancy Apr 15 '20 at 17:41
  • @CoolMind have you worked with koin dependcy injection as well – Edgar Apr 15 '20 at 17:43
  • @Nancy, do you use Dagger, Koin or Kodein? – CoolMind Apr 15 '20 at 17:45
  • @CoolMind no I don't – Nancy Apr 15 '20 at 17:46
  • @sashabeliy, thanks for the hint, sorry, I tried it a bit 2 years ago, but forgot. – CoolMind Apr 15 '20 at 17:46
  • @Nancy, that's strange. Could you write a code with `onAttach()`? Do you extend `Fragment` or abstract class? Please, also attach a screenshot with the error. Or did you extend `Activity` instead of `Fragment`? – CoolMind Apr 15 '20 at 17:50
  • @Nancy please check instead fragment you can use https://github.com/dipenptl1/Navigation-Drawer-With-Multiple-Activity multiple activity good luck – Edgar Apr 15 '20 at 17:51
  • @CoolMind I can but they code is slightly different than your suggestion, the `onAttach` and `super.onAttach` are both crossed out and the parameters say `@NonNull Activity activity` – Nancy Apr 15 '20 at 17:53
  • @Nancy, did you insert a correct `onAttach`? There are 2: usual and deprecated. Usual is `public void onAttach(Context context)` and deprecated is `public void onAttach(Activity activity)`, see https://stackoverflow.com/questions/32083053/android-fragment-onattach-deprecated. – CoolMind Apr 15 '20 at 18:00
  • 1
    @CoolMind I added some images of what is happening with the `onAttach()` – Nancy Apr 15 '20 at 18:00
  • @CoolMind according to the link you provided the `super.onAttach()` should have `context` instead of `activity` – Nancy Apr 15 '20 at 18:03
  • @Nancy, thanks! Sorry! I made a mistake. `super.onAttach(context);`. – CoolMind Apr 15 '20 at 18:08
  • @CoolMind Important thing is I'm no longer getting any warnings! – Nancy Apr 15 '20 at 18:15