![](/img/trans.png)
[英]How to retain app EditText data when Android app process restarts
[英]Android: How to save objects initialised in the Application class when the System Restarts my App Process
在我的應用程序類中,我有一個由啟動器屏幕啟動的所有活動使用的對象 。 問題是,在內存不足的情況下,系統會自動重新啟動我的應用程序(我可以在“設置”->“應用程序”->“運行進程”選項卡中看到它)。 由於它正在重新啟動(一旦應用程序在后台運行,就會發生這種情況),因此我一直在使用的Object被重置為null。
我的場景:
在啟動器活動中,我進入數據庫並在線程中獲取值,並使用Setter&Getter在Application類中設置Object值。
設置好之后,我從那里開始進行四個活動A(Launcher)-> B-> C-> D
現在我要進入后台,並且我的設備正在內存不足中運行,此時我的進程被殺死並重啟(即在后台)。
在重新啟動時,我的對象將重置為null,現在,如果我從最新列表或通過啟動器啟動應用程序,則在上述情況下,它仍是從我進入背景的位置啟動的最后一個活動,即活動D,正在訪問拋出Null指針的對象。
我的問題是
您可以執行諸如使用“共享首選項”之類的操作來保存有關對象的數據以便重建它。 (您也可以使用db,本地文件等)。
但是,如果我可以偏離特定的問題:您知道為什么您的應用程序由於內存原因而被終止嗎? 您是針對真正的低端設備還是硬件? 還是您的應用需要優化一點保存/重用內存?
您保存對象onSaveInstanceState的最后狀態並返回onRestoreInstanceState您可以在此最佳實踐中找到有關重新創建Activity的所有信息。 我建議您閱讀活動生命周期
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.