如何正确保存和恢复活动的状态?

时间:2016-07-13 03:10:32

标签: android

我正在学习如何使用Android Studio,而我正试图保存我的活动的状态。 onSaveInstanceState方法有问题,因为当我运行代码时,savedInstanceState始终为null。我该怎么办才能解决问题?我已经尝试了几个小时,我只是没有看到什么是错的。这是mainActivity文件的相关内容。

public class MainActivity extends AppCompatActivity {

    public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
    static final String LAST_MESSAGE = "com.example.myfirstapp.LAST_MESSAGE";
    String message, displayMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        System.out.println("Restoring");
        System.out.println(savedInstanceState);
        if (savedInstanceState != null) {
            displayMessage = "Last Saved Message: " + savedInstanceState.getString(LAST_MESSAGE);
        }
        else {
            displayMessage = "No Messages Saved!";
        }

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, displayMessage, Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        savedInstanceState.putString(LAST_MESSAGE, message);

        super.onSaveInstanceState(savedInstanceState);
    }

    public void sendMessage(View view) {
        Intent intent = new Intent(this, DisplayMessageActivity.class);
        EditText editText = (EditText) findViewById(R.id.edit_message);
        message = editText.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }
}

1 个答案:

答案 0 :(得分:0)

首先,您必须了解Activity Lifecycle。 https://developer.android.com/guide/components/activities.html

还读这个。 When are onSaveInstanceState() and onRestoreInstanceState() called, exactly?

简而言之,savedInstanceState在第一次执行活动时应为null。当您从任何页面返回MainActivity时,您可能会从onRestoreInstanceState获得一些内容。