SavedInstanceState为null

时间:2014-11-14 21:50:50

标签: java android

我想在我"同步"时获得当前系统时间与另一个设备。因此,通常在同步后调用/显示此活动。

目前,当前的系统时间是正确的,但我也有警报弹出另一项活动,一旦我完成了该活动,我想回到此活动。一旦我这样做,系统时间就会更新到最新的当前时间而不是旧的当前时间(这就是我想要的)。

我尝试使用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);,但仍然无法正常工作。

2 个答案:

答案 0 :(得分:1)

覆盖onRestoreInstanceState(Bundle savedInstanceState)以恢复日期。

另外,在你的onSaveInstanceState方法中调用'super.onSaveInstanceState`作为最后一个语句。

答案 1 :(得分:1)

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

编辑:对不起 - 本打算发表评论