Home > database >  How to keep information when I change layout android studio
How to keep information when I change layout android studio

Time:09-29

Let's assume that my Android app has an activity_main.xml and a second_layout.xml. In each of them there is a button and an editText.

The buttons allows me to change layout. Any time I switch from a layout to another, the content of the ediTexts is deleted. Can anyone tell me how to keep it?

I tried using the methods onSaveInstanceState(Bundle outState) and onRestoreInstanceState(Bundle outState) but it doesn't work.

Here's part of my code:

    editTextSingleLW = (EditText) findViewById(R.id.editTextSingleLW);
    String single_LW;

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString("Single_LW",singleLW);

        super.onSaveInstanceState(outState);
    }

    @Override
    public void onRestoreInstanceState(Bundle outState){
        super.onRestoreInstanceState(outState);

        editTextSingleLW.setText(outState.getString("Single_LW") "");
    } 

Any idea?

Thank You very much.

CodePudding user response:

intead of using overriden onRestoreInstanceState use same restoring code in onCreate(Bundle savedInstanceState) using its savedInstanceState argument. best approach would be to implement shared method for restoring data and call it in both onCreate and onRestoreInstanceState (remember to check if Bundle is null, as at very first start of Activity it is in onCreate)

  • Related