我有活动A和B.在活动A中,我加载数据然后当单击列表时它将我移动到活动B.当返回活动A时,数据再次加载。如何防止这种情况?
答案 0 :(得分:0)
当您从一个活动移动到另一个活动时,例如从活动A移动到活动B,那么您加载的数据将丢失。要防止数据重新加载,您需要覆盖onSaveInstanceState(Bundle savedInstance)。
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(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.
}
您可以通过覆盖onRestoreInstanceState(Bundle savedInstance)来提取这些值。
@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");
}
您还可以存储和检索arraylist。