Saving whole instance of an activity

314 Views Asked by At

Is there any simple way to save the whole activity instance and restoring it ?
After spending 1 hour of searching all corners of internet, I ended up here. I still don't know how to make this.

Yes, I know how to save current instance using onSaveInstanceState and onRestoreInstanceState but no one in the internet explained it with a large complex coding like dynamically created views, many textviews and calculations,etc.

Everyone explaining this with only one or two textViews and I was like "How someone can create an app with only few TextViews!?!" like below:

onSaveInstanceState()

protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    Log.i(TAG, "onSaveInstanceState");
    
    final EditText textBox = 
            (EditText) findViewById(R.id.editText);
    CharSequence userText = textBox.getText();
    outState.putCharSequence("savedText", userText);

}

onRestoreInstanceState()

    @Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
   super.onRestoreInstanceState(savedInstanceState);
   Log.i(TAG, "onRestoreInstanceState");

   final EditText textBox =
        (EditText) findViewById(R.id.editText);

   CharSequence userText =
                savedInstanceState.getCharSequence("savedText");

   textBox.setText(userText);
}

I can totally understand this above method. But What to do if we complete a quite complicated coding and want to save & restore the state I have completed all my complex coding stuff and landed in this problem.
I'm sure there will be a simple way to achieve this. Please understand my problem. Help me.
1

There are 1 best solutions below

0
GolnazTorabi On

If I understand correctly, you want to save the current state of the page even the page changes, if this is the case, it can be solved by data binding as follows:
1.enable data binding in Gradle
2. in XML file put your layout into layout tag

<layout>
 ...// your activity view layout
</layout>
  1. then define it in your activity :

    private lateinit var binding: FragmentNameBinding

4.add this expression in onCreate or onCreateView(for fragment)

if (!(::binding.isInitialized)) {
  //initialize you layout file and what ever you want 
   }
  //then initialize what you want to not change  after the layout 
  changed and back to it