Post

Android Fragment Lifecycle and savedInstanceState Debugging

Android Fragment Lifecycle and savedInstanceState Debugging

Background

In high school, I developed an app called “Dongcheon Alimi” for fellow students. It was a convenience app providing meal info, timetables, announcements, etc.

One day, users started reporting a bug. The app would crash at seemingly random times. Log analysis showed NullPointerException, but I couldn’t figure out where it came from.


Debugging Process

Spent 2 weeks on this. During that time, I learned a lot about Android Fragment lifecycle.

What I Discovered:

The app was using ViewPager + Fragment structure. When the user changed tabs, previous Fragments were being destroyed and recreated.

1
2
3
4
5
6
7
// Original code - the problem
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    // Accessing data initialized in onCreate
    textView.setText(data.getTitle());  // data is null!
}

When the Fragment was recreated, onCreate was called again but data was not recovered.


Root Cause

When Android destroys and recreates a Fragment (due to memory pressure, screen rotation, etc.), you must save state using onSaveInstanceState and restore it from savedInstanceState.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("title", data.getTitle());
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        String title = savedInstanceState.getString("title");
        // Restore data
    }
}

Solution

Saved necessary data in onSaveInstanceState and restored it from savedInstanceState when Fragment is recreated.


Lessons Learned

  • Understanding Fragment lifecycle is crucial for Android development
  • Fragments can be destroyed and recreated anytime
  • Must use savedInstanceState to preserve state
  • 2 weeks on one bug was rough, but learned deep debugging

From developing “Dongcheon Alimi” app in high school. (Published on Play Store, promoted through student council, acquired real users)

This post is licensed under CC BY 4.0 by the author.