我想在与其他设备“同步”时获取当前系统时间。因此,此活动通常在同步后调用/显示。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