Activity State

I have two actions A, B. Now from A I call B by pressing the button (using startActivity() ), then click the back button to return to A. Now that I press the button again to go to B, fresh activity is invoked (as expected).

Now can someone tell me how to show the previous state of B?

I read this article Saving Android Activity State Using Save Instance State , but Could Not Help It :(

 public class B extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main1); if(savedInstanceState!=null){ EditText editText=(EditText)findViewById(R.id.editText1); editText.setText(savedInstanceState.getString("EditBox")); } } @Override protected void onSaveInstanceState(Bundle onSaveInstanceState) { System.out.println("B.onSaveInstanceState()"); super.onSaveInstanceState(onSaveInstanceState); onSaveInstanceState.putString("EditBox","Hello"); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { System.out.println("B.onRestoreInstanceState()"); super.onRestoreInstanceState(savedInstanceState); EditText editText=(EditText)findViewById(R.id.editText1); editText.setText(savedInstanceState.getString("EditBox")); }} 

My class A

 public class A extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button=(Button)findViewById(R.id.button1); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i=new Intent(StartActivityforresultActivity.this,B.class); startActivity(i); } }); } 
+4
source share
1 answer

With what it seems like you're trying to do, you have two options: 1. Save state B when B is called onDestroy or onBackPressed. You will need to store this in memory or write it with some persistence (SharedPreferences, local file, etc.). Then, when B starts up, check if this data exists and if it uses state to load. 2. Override onBackPressed so that you do not call super.onBackPressed when pressed. Instead, start an instance of action A and set your goal flags FLAG_ACTIVITY_REORDER_TO_FRONT before calling startActivity. So something like this:

  Intent intent = new Intent(this, A.class); intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivity(intent); 

Now, when you click back, it should find instance A that is in your activity stack, and just bring it to the fore. You may need to add the same flag when starting B.

+6
source

Source: https://habr.com/ru/post/1384039/


All Articles