简体   繁体   中英

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.

Here is the OnCreate() for the first activity:

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

@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.

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); as the first line in onSaveInstanceState method.

Next you need to put

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

             txtClient.setText(client);
  }

into the onRestoreInstanceState method. onCreate is only called when re-drawing the app.

它显示为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 . thats why it always return null.

to save data you have onsaveinstance method and to restore you have onrestoreinstance method.

onSaveInstanceState() is a method used to store data before pausing the activity.

onRestoreInstanceState() is method used to retrieve that data back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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