0

I'm new programming in android. Recently I've been doing a project with Android studio. In my application, I'm creating an activity with two options for the user with two toggle buttons.

The user can choose if the buttons make a sound or vibrate.

The toggle button works perfectly, but when the user returns to the Main Activity and comes again to the options, the toggle button doesn´t save the settings that the user has chosen.

Example:

  1. (Go to Options)/ in Options the user chooses Sound/off & Vibrate/off
  2. back to (Main Activity)
  3. (GO to Options Again) The settings are restarted Sound/on & Vibrate/on

I hope someone can help me with this problem!

Sebastian Zartner
  • 18,808
  • 10
  • 90
  • 132
Danny908
  • 421
  • 2
  • 6
  • 20

1 Answers1

0

Android has a facility for persisting Activity (or Fragment) state.

If your Activity is put into background it might be destroyed at some point and you don't have control over it. This is why Android uses Bundles. Store your data inside the bundle then read it back in

onCreate(Bundle savedInstanceState)

so before your activity dies for any reason, store important values:

protected void onSaveInstanceState(Bundle bundle) {
    bundle.putInt(SOME_IMPORTANT_INT,mMyInt);
    bundle.putString(SOME_IMPORTANT_STRING,mMyString);
}

when activity is created we have to read what is in the bundle (if there is anything at all):

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(savedInstanceState != null) {
        mMyInt = savedInstanceState.getInt(SOME_IMPORTANT_INT);
        mMyString = savedInstanceState.getString(SOME_IMPORTANT_STRING);
    }
}

In short, what ever happens to your activity mMyInt and mMyString values are restored.

We might have a little control over when activity are restarted. This is done by android:configChanges attribute in the AndroidManifest file:

<activity
    android:name=".ui.login.LoginActivity"
    android:configChanges="orientation|keyboardHidden|screenSize"
    android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

http://developer.android.com/guide/topics/resources/runtime-changes.html

robotoaster
  • 3,082
  • 1
  • 24
  • 23