2012-03-02 38 views
0

我有這個筆記應用程序,用戶可以輸入他想要的文本框。但是我也希望即使用戶退出應用程序,文本仍然存在。我如何在notes.java代碼中應用onSavedInstantState和RestoreinstantState?如何將onSavedInstantState應用於此java代碼?

public class notes extends Activity{ 

    /** Called when the activity is first created. */ 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.notes); 

     Button wg = (Button) findViewById(R.id.button3); 
     wg.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View view) { 
       Intent intent = new Intent(); 
       setResult(RESULT_OK, intent); 
       finish(); 
      } 

     }); 



    } 
} 
+0

嘗試這種情況: [http://stackoverflow.com/questions/6525698/how-to-use-onsavedinstancestate-example-please][1] [1]:HTTP: //stackoverflow.com/questions/6525698/how-to-use-onsavedinstancestate-example-please – Simon 2012-03-02 17:34:14

回答

0

另一種方式來保存狀態之外onRetainNonConfigurationInstance()(它不建議使用)是的onSaveInstanceState

的onSaveInstanceState和它相關的方法是鉤子,告訴你一些事情正在發生,你可能想保存/恢復。這些通常稱爲配置更改,但如果應用程序已由android關閉,也會發生這種情況。

可以覆蓋這些方法很像你的onCreate做:

@Override 
public void onSaveInstanceState(Bundle bundle) 
{ 
    //Now you must either save it to memory, the db, a preference, or somwhere else 
    bundle.putSerializable("some key", objectToSave); 
    super.onSaveInstanceState(bundle); 
} 

然後你就可以得到那個對象回來的onCreate通過在束傳遞。

如果應用程序退出,則需要做的不僅僅是將其保存到包中。你必須堅持到別的地方,並在需要時手動加載它。

+0

對於「objecttosave」我該怎麼取代它? – 2012-03-02 20:20:34

+0

您擁有的任何類都是Serializable(實現java.io.Serializable)。這個類應該包含你想要保存在內存中用於屏幕旋轉等配置更改的所有內容。 – Shellum 2012-03-02 20:50:49

+0

所以我只是這樣做? (「一些關鍵」可序列化)我不明白對不起:/ – 2012-03-02 21:03:53