小能豆

How can I save an activity state using the save instance state?

android

I’ve been working on the Android SDK platform, and it is a little unclear how to save an application’s state. So given this minor re-tooling of the ‘Hello, Android’ example:

package com.android.hello;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class HelloAndroid extends Activity {

  private TextView mTextView = null;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mTextView = new TextView(this);

    if (savedInstanceState == null) {
       mTextView.setText("Welcome to HelloAndroid!");
    } else {
       mTextView.setText("Welcome back.");
    }

    setContentView(mTextView);
  }
}

I thought it would be enough for the simplest case, but it always responds with the first message, no matter how I navigate away from the app.

I’m sure the solution is as simple as overriding onPause or something like that, but I’ve been poking away in the documentation for 30 minutes or so and haven’t found anything obvious.


阅读 212

收藏
2023-12-26

共1个答案

小能豆

In Android, to save and restore an application’s state across activities and lifecycle changes, you can override the onSaveInstanceState and onRestoreInstanceState methods. These methods allow you to persist and retrieve data when your activity is paused or stopped.

Here’s how you can modify your HelloAndroid example to handle state persistence:

package com.android.hello;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class HelloAndroid extends Activity {

  private static final String KEY_TEXT = "text_key";
  private TextView mTextView = null;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mTextView = new TextView(this);

    if (savedInstanceState == null) {
       mTextView.setText("Welcome to HelloAndroid!");
    } else {
       // Restore the text from the saved state
       mTextView.setText(savedInstanceState.getString(KEY_TEXT, "Welcome back."));
    }

    setContentView(mTextView);
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // Save the current text to the bundle
    outState.putString(KEY_TEXT, mTextView.getText().toString());
  }
}

In this example:

  • The onSaveInstanceState method is overridden to save the current text of the TextView into the Bundle provided as an argument.
  • In the onCreate method, if savedInstanceState is not null, it means the activity is being recreated, and the saved text is restored from the bundle.

This way, the application’s state is persisted across lifecycle changes, and you should see the correct message even after navigating away from the app.

2023-12-26