Android Fragment Lifecycle
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 ofgetLifecycle(). - Use
childFragmentManagerfor nested fragments. - Call
commitNow()only aftersuper.onResume(). - Replace
onActivityCreatedwithonViewCreated.
Common Mistakes with fragment lifecycle
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro