-2

So I followed Google's first Android app sample. If I tapped the send button, it opened up the DisplayMessageActivity. But upon tapped the back button (left arrow) from the DisplayMessageActivity, the onCreate(Bundle savedInstanceState) of the MainActivity got called again. It looks like it created a new instance of MainActivity. I could verify this by setting a bool value in onCreate of MainActivity and it was not retained.

How do you go back to the previous instance of MainActivity (the caller)?

hata
  • 11,633
  • 6
  • 46
  • 69
user523234
  • 14,323
  • 10
  • 62
  • 102

3 Answers3

1

You should have a look at Androids Activity Lifecycle.

If you want to access the state of the activity again, I would suggest to use the method

public void onSaveInstanceState(Bundle outState)

to save the current state.

Retrieve the previously saved values in this method:

public void onRestoreInstanceState(Bundle savedInstanceState)`

An example can be found here

Markus
  • 98
  • 1
  • 7
  • The onSaveInstanceState never got called. So this if (savedInstanceState != null) in the onCreate did not occur. – user523234 May 11 '20 at 17:24
  • hmm, the method `onSaveInstanceState` should be called when the Activity gets destroyed. As you said, if the method `onSaveInstanceState` never gets called, the param in the `onCreate` will be `null`. Are you sure the OnSaveInstanceState is correctly written (in the MainActivity) with the `@Override` annotation? – Markus May 11 '20 at 19:09
0

You can call finish() in the onClickListener of the back arrow view. It will finish the DisplayMessageActivity and you will return to the caller activity (MainActivity in your case).

Something like:

backArrow.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
       finish();
   }
});
Carlie45
  • 1
  • 1
0

It looks like it created a new instance of MainActivity.

Yes, I think, that was quite a normal behavior.

Basically, Android OS would keep only one Activity at once so that free as many memory resources as possible.

You should design your application with understanding about such lifecycle concepts.

You can save some of the states of your Activity in certain manners (Parcelable, Bundle or SharedPreferences, etc.).

hata
  • 11,633
  • 6
  • 46
  • 69