[英]SavedInstanceState is null
當我與另一台設備“同步”時,我想獲取當前系統時間。 因此,通常在同步后立即調用/顯示此活動。
當前,當前系統時間是正確的,但是我還彈出了另一個警報,該活動結束后,我想返回該活動。 完成后,系統時間將更新為大多數當前時間,而不是舊的當前時間(這就是我想要的時間)。
我嘗試使用SavedInstanceState
保存舊的當前時間的狀態,盡管它確實在onSavedInstanceState
中獲得正確的字符串。 當我回到此活動時, SavedInstanceState
為null。 不知道為什么
public class InfoActivity extends BaseActivity {
String fileLastSync = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info);
Resources resources = context.getResources();
if (savedInstanceState != null) {
// Restore value of members from saved state
fileLastSync = savedInstanceState.getString("FileLastSync");
} else {
//Gets the current DateTime
long nextTime = (System.currentTimeMillis());
Date date = new Date(nextTime);
//Formats the current DateTime
SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy HH:mm a");
String formatDate = format.format(date);
//Last sync time is the current formatted date
fileLastSync = formatDate;
}
//Gets the 'last synced' string and sets to datetime of the last sync
String syncString = String.format(resources.getString(R.string.last_sync), fileLastSync);
//Dynamically sets the datetime of the last sync string
TextView lastSyncTextView = ((TextView) findViewById(R.id.last_sync) );
lastSyncTextView.setText(syncString);
}
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("FileLastSync",fileLastSync);
super.onSaveInstanceState(savedInstanceState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null) {
// Restore value of members from saved state
fileLastSync = savedInstanceState.getString("FileLastSync");
} else {
//Gets the current DateTime
long nextTime = (System.currentTimeMillis());
Date date = new Date(nextTime);
//Formats the current DateTime
SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy hh:mm a");
String formatDate = format.format(date);
//Last sync time is the current formatted date
fileLastSync = formatDate;
}
}
}
編輯:我試圖把它放在: super.onSaveInstanceState(savedInstanceState);
在該方法的末尾,但仍然無法正常工作。
覆蓋onRestoreInstanceState(Bundle savedInstanceState)
以在那里恢復日期。
同樣,在您的onSaveInstanceState
方法中,調用“ super.onSaveInstanceState”作為最后一條語句。
您不應將相同的代碼從onSave放入onRestore。 而是將完整的if語句從onCreate方法復制到onRestore方法。 並調用super.onRestoreInstanceState作為第一條語句。
編輯:對不起-本來是要發表評論
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.