gpt4 book ai didi

java - SavedInstanceState 为空

转载 作者:行者123 更新时间:2023-12-02 05:16:12 25 4
gpt4 key购买 nike

我想在与另一台设备“同步”时获取当前系统时间。因此,此 Activity 通常在同步后立即调用/显示。

目前,当前系统时间是正确的,但我还弹出另一个 Activity 的警报,一旦我完成该 Activity ,我想返回到该 Activity 。一旦我这样做,系统时间将更新为最新时间,而不是旧的当前时间(这就是我想要的)。

我尝试使用SavedInstanceState来保存旧当前时间的状态,并且它确实在onSavedInstanceState中获取了正确的字符串。当我返回此 Activity 时,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); 放在方法的末尾,但仍然不起作用。

最佳答案

您不应将 onSave 中的相同代码放入 onRestore 中。将完整的 if 语句从 onCreate 方法复制到 onRestore 方法中。并调用 super.onRestoreInstanceState 作为第一条语句。

编辑:抱歉 - 本来是一条评论

关于java - SavedInstanceState 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26939420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com