user1275954
user1275954

Reputation: 36

Android fragments not saving states, crashing on rotation/screen lock/back

My application is crashing whenever I lock the screen, go back, rotate the screen, or hit the home screen. This application implements a fragment UI with 3 tabs. In my manifest, I have android:configChanges="orientation", and this was working, until I changed something(I don't remember what it was). Now even with that in my manifest, my app can't handle rotation changes. I'm trying to implement onSaveInstanceState, onRestoreInstanceState, onPause, and onResume, but it continues to crash. Here is some of the code:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Inflate the layout
    setContentView(R.layout.main);

    // Initialize the TabHost
    this.initializeTabHost(savedInstanceState);
    if (savedInstanceState != null) {
         // set the tab as per the saved state
        mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
    }
    // Initialize ViewPager
    this.initializeViewPager();

}   

@Override
protected void onPause() {
    super.onPause();       
    }

 @Override
protected void onResume() {
super.onResume();         
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("tab",
            mTabHost.getCurrentTabTag()); // save the tab selected

}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    String myString = savedInstanceState.getString("tab");

}

LOGCAT for Application launch & crash

Upvotes: 0

Views: 2077

Answers (1)

lrAndroid
lrAndroid

Reputation: 2854

super.onSaveInstanceState(outState);
outState.putString("tab",
        mTabHost.getCurrentTabTag()); // save the tab selected

should be

outState.putString("tab",
        mTabHost.getCurrentTabTag()); // save the tab selected

super.onSaveInstanceState(outState);

You need to add "tab" to outState before calling onSaveInstanceState in order to avoid an exception when loading it in OnCreate. In other words, your "tab" is never actually being saved, since you are saving the state before adding "tab" to the state.

Upvotes: 2

Related Questions