2011-10-14 117 views
0

我在應用程序中使用了兩個活動(A和B)的實例。現在我面臨着堅持每個人的問題。當我使用sharedpreferences時,我只能用SharedPreferences保存A.class和B.class,但是當我再次使用實例A時。 SharedPreferences中的持久狀態被重寫。我認爲,我應該使用Bundle與onSavedInstanceState和onRestoredInstanceState。但如何將保存的Bundle傳遞到onCreate()?目標是能夠堅持活動實例。Android - 持久化活動實例

感謝

+0

更多細節在這裏給出//stackoverflow.com/questions/151777/how-do-i-save-an-android-applications-state –

回答

0

當啓動活動答:您可以使用intent.putExtra(String name, Bundle value)的包傳遞到您的活動,然後在活動A的onCreate使用getIntent.getBundleExtra(String name)再次得到你的包。

+0

問題是,活動A是一個開始的意圖,我不知道如何存儲Bundle。我正在使用一個活動的多個實例,每個實例都必須堅持 – Waypoint

0

你需要考慮你需要堅持什麼狀態。

例如;

  • 哪個複選框被打勾?
  • 用戶在什麼級別?
  • 什麼是他們的光標

的位置作爲一個例子, 我剛完成的應用程序,其中用戶可以查看不同級別的卡片的。

我在乎;

  • 他們正在尋找在哪個級別燒錄卡(也許他們在2級)
  • 這卡是他們尋找的(也許他們是4卡)

這裏的碼。 HTTP:

// a variable to store the level 
private final static String CARD_LEVEL_STATE = "currentCardLevel"; 

// a variable to store the current card 
private final static String CURRENT_CARD_STATE = "currentCardNumber"; 

@Override 
protected void onSaveInstanceState(Bundle outState) { 
    // save the level 
    outState.putInt(CARD_LEVEL_STATE, flashCardList.currentLevel()); 
    // save the current card 
    outState.putInt(CURRENT_CARD_STATE, flashCardList.currentCardNumber()); 
    // do the default stuff 
    super.onSaveInstanceState(outState); 
} 

@Override 
protected void onRestoreInstanceState(Bundle savedInstanceState) { 
    // ignore if we have no saved state 
    if (savedInstanceState != null) { 
    // record the level 
    if (savedInstanceState.containsKey(CARD_LEVEL_STATE)) { 
     int currentCardLevel = savedInstanceState.getInt(CARD_LEVEL_STATE); 
     flashCardList.setCardLevel(currentCardLevel); 
    } 
    // recover the current card 
    if (savedInstanceState.containsKey(CURRENT_CARD_STATE)) { 
     int currentCardNumber = savedInstanceState.getInt(CURRENT_CARD_STATE); 
     flashCardList.setCurrentCardNumber(currentCardNumber); 
    } 
    // refresh the view 
    refreshCard(); 
    } 
    super.onRestoreInstanceState(savedInstanceState); 
}; 
+0

那麼結果如何?我是否只能使用onSaveInstanceState和onRestoreInstanceState事件,儘管我正在使用多個活動實例?我想堅持數據結束GUI狀態 – Waypoint

+0

當你交換一個活動時,Android會調用活動的'onRestoreInstanceState'方法。這是你應該恢復狀態的時候。無論是創建一個新的實例,還是交換到之前的現有實例,都取決於android。你不應該嘗試手動持久化一個實例。你只需要告訴android如何保存和加載你關心的狀態。 –

+0

好的,但是這就產生了問題 - 如何存儲Bundle?在方法onSaveInstanceState中,讓我們說我將它保存爲某個文件,或像一個字符串保存到SharedPreferences中。應用程序被系統關閉,現在我需要恢復實例。爲此,有一個方法onRestoreInstaneceState,但它需要Bundle作爲參數。這個捆綁包不存在,它必須先加載。但是在哪裏加載它? – Waypoint

相關問題