2017-08-08 49 views
-4

我有活動A和B.在活動A中,我加載數據,然後在單擊列表時將它移動到活動B.當返回到活動A時,數據再次加載。如何防止這一點?在活動中有活動A和B

+0

你能分享你的代碼嗎? –

+0

[如何完成在Android中啓動其他活動時的活動?](https://stackoverflow.com/questions/18957125/how-to-finish-activity-when-starting-other-activity-in-android) –

回答

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。

相關問題