0

I am working on an application but I'm unable to understand savedInstanceState properly when it occurs:

package com.android.Test;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class Test extends AppCompatActivity {

   private TextView mTextView = null;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState == null) {
       Toast. makeText(getApplicationContext(),"welcome",Toast. LENGTH_SHORT).show();
    } else {
       Toast. makeText(getApplicationContext(),"Thanks visit again",Toast. LENGTH_SHORT).show();
    }
  }
}

how does the activity work when app closes and opens after a long time. is there any other method for achieving this using savedInstanceState or onRestoreInstanceState.

MehranB
  • 1,460
  • 2
  • 7
  • 17
  • `savedInstanceState` will be different than null when you rotate the device. Note that you have to unlock the orientation on your device and not having any rule to block activity recreation on your manifest. – madlymad Dec 07 '20 at 08:04

2 Answers2

1

The savedInstanceState is a reference to a Bundle object that is passed into the onCreate method of every Android Activity.

The onCreate() expects to be called with a Bundle as parameter so we pass savedInstanceState.

Activities have the ability, under special circumstances, to restore themselves to a previous state using the data stored in this bundle. If there is no available instance data, the savedInstanceState will be null.

For example, the savedInstanceState will always be null the first time an Activity is started, but may be non-null if an Activity is destroyed during rotation, because onCreate is called each time activity starts or restarts.

Majid Ali
  • 485
  • 6
  • 17
0

When your app enters in the background and android needs the system resources (cpu time, memory) for other tasks or apps, your app will enter the savedInstance and the overrided method onSaveInstanceState(Bundle outState) is called. When the user re enters the activity the savedInstanceState in onCreate(Bundle savedInstanceState) will not be null, so you can recreate the required parameters for your activity, which have been saved before.

With enabled "Don't keep activities" under the developer options menu you can force this behavior and every time you are leaving your activity, your app calls onSaveInstanceState.

private String restored_string;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    if (savedInstanceState != null){
        
       restored_string = savedInstanceState.getString("key");
    }
}



@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("key", "string value");
}
TomInCode
  • 506
  • 5
  • 11