0

I've got two activities, A and B. Activity B can be opened by pressing a button in Activity A.

In activity B I have an integer variable which I would like to keep for when I return to activity B from A. My problem is when I press the back button to go from B to A the activity is destroyed.

I have overwritten the onBackPressed method to:

@Override public void onBackPressed(){ Intent i = new Intent(this, Game.class); startActivity(i); }

I can see from my logs that activity B is in the state onStop() after back button is pressed, however, onRestart() is not being called so the activity must be getting killed for memory reasons.

I have read answers to other posts suggesting I use onSaveInstanceState() but when I try to access the bundle in onCreate() the bundle is null. Method onRestoreInstanceState() does not get called.

 protected void onSaveInstanceState(Bundle savedInstanceState){
    Log.i(LOG, "instance saving");
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putInt("score", userScore);
}

I have also tried SharedPreferences but this is not useful because I do not want my data to persist when the activity/application is intentionally destroyed.

Wowlock
  • 3
  • 2

3 Answers3

0

I think your problem is in understanding the whole Task ecosystem. When you press back button you pop out your activity from the Task, because of that it is destroyed and onDestroyed() is called.
To sum-up I think you are just getting every time a brand new activity. onSaveInstanceState() isn't called because activity is killed by user, not by the OS.
Take a deeper look at this developer tutorial.
Also I think those two must be helpful : me and me!

Community
  • 1
  • 1
Yurii Tsap
  • 3,554
  • 3
  • 24
  • 33
-1

you can store variables in the app class https://developer.android.com/reference/android/app/Application.html or you can make your own singleton class for this https://www.tutorialspoint.com/design_pattern/singleton_pattern.htm

locomain
  • 185
  • 1
  • 15
-1

Starting a Activity - A on onBackPressed will definitely kill the current Activity - B. Instead of starting Activity again just call onBackPressed in Activity - B and add a stage called onResume() which is called when you resume back to Activity B from A

Remove this:

@Override
public void onBackPressed(){
    Intent i = new Intent(this, Game.class);
    startActivity(i);
}

With this:

@Override
public void onBackPressed(){
    super.onBackPressed();
}   

When you coming back from A to B, in B @Override stage onResume() and in this you can save the value while coming back from Activity A.

Add this in Activity B:

@Override
protected void onResume() {
    super.onResume();
    // save values here for resume
}

Look the Activity Life Cycle:

enter image description here

W4R10CK
  • 5,502
  • 2
  • 19
  • 30