Skip to content

Android Fragment Lifecycle

DodaTech 2 min read

In this tutorial, you'll learn about Android Fragment Lifecycle. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

Fragments are notorious for lifecycle bugs: getActivity() returns null, IllegalStateException on commit(), or views referenced after destruction.

Wrong Approach ❌

public class MyFragment extends Fragment {
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Direct network call without lifecycle check
        new FetchTask().execute();
    }

    private void doSomething() {
        getActivity().runOnUiThread(() -> textView.setText("Hello")); // NPE!
    }
}

Output: NullPointerException when getActivity() returns null.

Right Approach ✅

public class MyFragment extends Fragment {
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        viewLifecycleOwner.getLifecycle().addObserver(new LifecycleObserver() {
            @OnLifecycleEvent(Lifecycle.Event.ON_START) void onStart() {
                // Safe: Activity and View are both alive
            }
        });
    }

    private void doSomething() {
        Activity activity = getActivity();
        if (activity != null && !isRemoving()) {
            activity.runOnUiThread(() -> {
                View v = getView();
                if (v != null) textView.setText("Hello");
            });
        }
    }
}

Output: Safe execution with null checks and lifecycle awareness.

Prevention

  • Always use getViewLifecycleOwner().getLifecycle() instead of getLifecycle().
  • Use childFragmentManager for nested fragments.
  • Call commitNow() only after super.onResume().
  • Replace onActivityCreated with onViewCreated.

Common Mistakes with fragment lifecycle

  1. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  2. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  3. Misunderstanding that String is [Char] with poor performance for large text operations

These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Why does getActivity() return null in my Fragment?

This happens when the Fragment is detached (onDetach() called) but your background task tries to access the Activity. Always null-check getActivity() or use viewLifecycleOwner.

### What is the difference between commit() and commitNow()?

commit() is scheduled on the main thread queue and may execute later. commitNow() executes immediately but throws if called after the state has been saved. Prefer commit() with isStateSaved() check.

### When should I use childFragmentManager vs parentFragmentManager?

Use childFragmentManager for fragments hosted inside another fragment (nested fragments). Use parentFragmentManager for fragments hosted by the Activity.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro