0

I have a few activities, on the Acivity 1 I set a variable active which is true.

Activity 1 => Activity 2 => come back to Activity 1

active=true => active=false => active=false 

I got:

Activity 1:

public boolean active = false;

onCreate() {active = true;}

Intent i = new Intent(Activity1.this, Activity2.class);
startActivity(i);

This activity must work in the background.

Activity 2:

public boolean active = false;

Intent intent = new Intent(Activity2.this, Activity1.class);
        intent.putExtra("active", active);

then I call method onBackPressed();

But when I come back Activity 1 appears and I obtain active = true:

onResume() and onRestart() here I have:

Intent intent = getIntent();
active = intent.getBooleanExtra("active", active);

When I tried to use startActivityforResult() method from Activity 1 it doesn't move to the Activity 2 and it's still true.

May be its because I have a main layout in both activities and contents changes. How to resolve this?

Piotr M.
  • 11
  • 7

2 Answers2

0

This answer could help you. In short: you can use SharedPreferences to save any variables for coming back to them later thru any activities.

SharedPreferences prefs = getSharedPreferences("preference_file_name", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("variable_key", variable);
editor.commit();

Additionally, even with startActivityForResult you can pass some data.

Max
  • 1,341
  • 3
  • 20
  • 39
0

You can use shared preferences to store the variable as mentioned in above answer but we can do this without using shared preferences as well.

  • Create global variable active and assign it to True.
  • Use startActivityforResult() to swittch between Activity 1 => Activity 2
  • on BackPressed(), OnActivityResult in Activity1 change the global variable value to false. And due to startActivityforResult, Activity1 was in Pause state and on coming back to Activity 1 onResume will be called which won't replace the Global variable.
Ankur Mishra
  • 103
  • 9