旋转屏幕时丢失数据

我的应用程序中有一个有趣的小错误。 当用户旋转屏幕我失去了我的活动中的一些数据。 任何人都知道为什么发生这种情况?

默认情况下,当屏幕旋转时,您的活动将被终止并重新启动。 为了确保没有数据丢失,您需要使用生命周期方法正确保存和恢复您的数据。 请参阅保存持久状态 。

 //Use onSaveInstanceState(Bundle) and onRestoreInstanceState @Override public void onSaveInstanceState(Bundle savedInstanceState) { // Save UI state changes to the savedInstanceState. // This bundle will be passed to onCreate if the process is // killed and restarted. savedInstanceState.putBoolean("MyBoolean", true); savedInstanceState.putDouble("myDouble", 1.9); savedInstanceState.putInt("MyInt", 1); savedInstanceState.putString("MyString", "Welcome back to Android"); // etc. super.onSaveInstanceState(savedInstanceState); } //onRestoreInstanceState @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); // Restore UI state from the savedInstanceState. // This bundle has also been passed to onCreate. boolean myBoolean = savedInstanceState.getBoolean("MyBoolean"); double myDouble = savedInstanceState.getDouble("myDouble"); int myInt = savedInstanceState.getInt("MyInt"); String myString = savedInstanceState.getString("MyString"); } 

这是当系统在循环中删除时保存数据的方式。

我发现最快的解决scheme是这样的: http : //developer.android.com/guide/topics/resources/runtime-changes.html#HandlingTheChange

这是@ jaisonDavis的有用答案的变体:

 int myInt; String myString; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_verses); if (savedInstanceState == null) { Intent intent = getIntent(); myInt = intent.getIntExtra("MyIntIntentKey", DEFAULT_INT); myString = intent.getStringExtra("MyStringIntentKey", DEFAULT_STRING); } else { // savedInstanceState has saved values myInt = savedInstanceState.getInt("MyIntKey"); myString = savedInstanceState.getString("MyStringKey"); } } @Override public void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.putInt("MyIntKey", myInt); savedInstanceState.putString("MyStringKey", myString); super.onSaveInstanceState(savedInstanceState); } 

在这个例子中,variables从第一次创build活动时从一个Intent初始化,但之后,他们从savedInstanceState被初始化(就像方向改变时)。