locked
How to restore the instance state RRS feed

  • Question

  • User378211 posted

    I want to preserve program data when the user runs another program. So if the user puts, say, her name into a text box and then goes to another app, when he comes back to the program I want the name in the text box.

    This works during debug. Here's my code:

    protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState);

    and here's how I save the instance data:

    public void onSaveInstanceState(Bundle savedInstanceState) { //super.onSaveInstanceState(savedInstanceState); // Save UI state changes to the savedInstanceState. // This bundle will be passed to onCreate if the process is // killed and restarted.

            savedInstanceState.PutString("txtName", txtName.Text);
    

    etc.

    Again, this works perfectly (it seems to me) in debug but not in release mode.

    Why?

    RON

    Friday, February 22, 2019 5:04 PM

Answers

  • User371688 posted

    You can try the method: onStop() which is called when the activity is no longer visible. When you come back, you can restore the value in method onStart(). Meanwhile , you can use ISharedPreferences in Xamarin Android to save the simple values.

    Just like this:

         protected override void OnStop()
        {
           ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (mContext);
           ISharedPreferencesEditor editor = prefs.Edit ();
           editor.PutString ("txtName", txtName.Text);
          // editor.Commit();    // applies changes synchronously on older APIs
          editor.Apply();        // applies changes asynchronously on newer APIs
            base.OnStop();
        }
    
    
        protected override void OnStart()
        {
         //Access saved values using:
         ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(mContext);
          string mName = prefs.GetString("txtName", < default value >);
          txtName.Text= mName;
          base.OnStart();
        }
    

    For more details: https://developer.android.com/guide/components/activities/activity-lifecycle

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Monday, February 25, 2019 5:43 AM