我想在與其他設備「同步」時獲取當前系統時間。因此,此活動通常在同步後調用/顯示。SavedInstanceState爲空
目前,當前系統時間是正確的,但我也有警報彈出另一個活動,一旦我完成了該活動,我想回到此活動。一旦我這樣做,系統時間會更新到最新的時間,而不是舊的當前時間(這正是我想要的)。
我試圖使用SavedInstanceState
保存舊的當前時間的狀態,並且它確實在onSavedInstanceState
中獲得正確的字符串。當我回到此活動時,SavedInstanceState
爲空。我不知道爲什麼?
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);
在方法的結束,但仍然無法正常工作。
'fileLastSync'聲明在哪裏? – 2014-11-14 21:57:07
看來你在''onCreate'裏面放了'onSaveInstanceState' **。檢查你的大括號。 – 2014-11-14 22:03:17
對不起,它在我的代碼之外。以上是一個片段。不是這個。 – 2014-11-14 22:06:36