简体   繁体   English

捆绑包saveInstanceState始终为null

[英]Bundle savedInstanceState is always null

I have two different activities, in the first one I enter some info into some EditTexts, I then go to the second activity, but when I return, the text that was on EditTexts in the first activity are gone. 我有两个不同的活动,在第一个活动中,我向一些EditText中输入一些信息,然后转到第二个活动,但是当我返回时,第一个活动中EditText上的文本消失了。

Here is the OnCreate() for the first activity: 这是第一个活动的OnCreate():

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.act_frm_recetas);

    txtClient = (EditText) findViewById(R.id.txtNombreCliente);

           if(savedInstanceState != null){
                 String client = savedInstanceState.getString("Client");

                 txtClient.setText(client);
            }
}

I'm using the onSaveInstanceState method to save the info 我正在使用onSaveInstanceState方法保存信息

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {

    String x = txtClient.getText().toString();
    savedInstanceState.putString("Client", x);

    super.onSaveInstanceState(savedInstanceState);
}

When doing a debug, I can see the savedInstanceState Bundle has indeed been filled in the onSaveInstanceState method, but in the OnCreate in shows null. 进行调试时,我可以看到onSaveInstanceState方法中确实填充了saveInstanceState Bundle,但在OnCreate中显示为null。

Maybe I have to add something in the second activity? 也许我必须在第二个活动中添加一些内容? I currently don't have anything in there other than a button that takes me back to the first activity. 目前,除了按钮之外,我什么都没有,它可以带我回到第一个活动。

You need to call super.onSaveInstanceState(savedInstanceState); 您需要调用super.onSaveInstanceState(savedInstanceState); as the first line in onSaveInstanceState method. 作为onSaveInstanceState方法的第一行。

Next you need to put 接下来你需要放

if(savedInstanceState != null) {
             String client = savedInstanceState.getString("Client");

             txtClient.setText(client);
  }

into the onRestoreInstanceState method. 放入onRestoreInstanceState方法。 onCreate is only called when re-drawing the app. 仅在重新绘制应用程序时调用onCreate

它显示为null,因为onCreate仅在首次创建该活动时才调用,当您从第二个活动返回时,它将恢复您的第一个活动。.尝试在onResume()方法上显示它

我的猜测是第一个活动尚未销毁,因此当您导航回第一个活动时,永远不会调用onCreate。

I guess onCreate is called when aactivity is going to load into memory, and at that time activity does not contain any thing . 我猜想当活动将要加载到内存中时onCreate被调用了,那时活动不包含任何东西。 thats why it always return null. 这就是为什么它总是返回null的原因。

to save data you have onsaveinstance method and to restore you have onrestoreinstance method. 要保存数据,请使用onsaveinstance方法,要进行还原,请使用onrestoreinstance方法。

onSaveInstanceState() is a method used to store data before pausing the activity. onSaveInstanceState()是一种用于在暂停活动之前存储数据的方法。

onRestoreInstanceState() is method used to retrieve that data back. onRestoreInstanceState()是用于检索该数据的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM