Search code examples
androidonsaveinstancestate

Button text gets reset on orientation change


In my android app, I am trying to solve an issue with orientation change.

I have a main layout where I have two buttons. On click of the first button (default text on this button is "Select a category"), a dialog box appears with a category list with categories displayed as radio buttons. After the user selects a category, the selected category name appears on the button. Now when I change the orientation in the emulator, the Button text gets reset again. I have used onSaveInstanceState() like below.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
// Initialization code

categoryList=(Button)findViewById(R.id.category_selection);

    if (savedInstanceState != null)
    {
        System.out.println("savedInstanceState--- 
        "+savedInstanceState.getString("bundle_category_name"));
        categoryName=savedInstanceState.getString("bundle_category_name");
        categoryList.setText(categoryName);
    }
    else
    {
        categoryList.setText(R.string.category);
    }
// remaining code 
}

@Override
public void onSaveInstanceState(Bundle outState)
{
    super.onSaveInstanceState(outState);
    // Save selected category name
    System.out.println("saving category name "+categoryName);
    outState.putString("bundle_category_name", categoryName);
}

I am able to get the category name back in onCreate(), the sysout prints correctly. But it is not getting set as the button text after change in orientation. Please let me know if I am doing anything wrong.

Thanks


Solution

  • Add android:configChanges="orientation|screenSize" in your Android Manifest file.

     <activity android:name="YourActivity"
      ...
      android:configChanges="orientation|screenSize"
      .../>