单击“后退"按钮后重新创建活动状态
当我成功地将数据保存到onSaveInstanceState方法中的Bundle时,我找不到为什么onCreate方法中的saveInstanceState总是为null的原因.当我在AVD上运行程序并单击后退"按钮(破坏活动),然后通过单击其图标再次创建它时,保存状态始终为null.这是一个测试此问题的简单程序.
I can't find out why savedInstanceState is always null in the onCreate method when I'm successfully saving data to the Bundle in onSaveInstanceState method. When I'm running my program on AVD and clicking back button(destroying activity) and then creating it again by clicking its icon the saved state is always null. Here is a simple program which tests this problem.
package com.example.myTestApp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.button);
if(savedInstanceState == null){
button.setText("No");
}else{
button.setText("Yes");
}
}
static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
private int mCurrentScore = 1;
private int mCurrentLevel = 2;
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
}
}
告诉我如何解决这个问题.
Tell me how to solve this problem if possible.
这是预期的.当您按回去时,活动将被销毁,它所拥有的数据将丢失.此后,当您重新打开应用程序时,您将始终在捆绑包中得到null,因为正在创建一个新的新实例.
That is expected. When you press back, the Activity is destroyed and the data it had is lost. After this you will always get null in the bundle as a new, fresh instance is being created when you reopen the app.
由于某些更改(例如旋转)或由于其在后台暂停了很长时间而重新创建活动时,将使用Bundle savedInstanceState包.
The Bundle savedInstanceState is used when the activity is being recreated due to some changes (like rotation), or because it was paused in the background for a long time.
如果您要保留一些数据,请为小型内容考虑SharedPreferences,或者为大型内容考虑数据库(SQLite,Realm)或文件.
If you want to persist some data, consider SharedPreferences for small stuff, or maybe a database (SQLite, Realm) or files for large stuff.