Reputation: 979
Let's say First.class has a variable String currentValue = "Red" with a button that leads to Second.class (an activity). First.class(Activity) displays in a textview what the variable currentValue happens to be. (Currently, Red).
If we push the button, it takes us to Second.class, which has an EditText box to modify the variable in First.class. It also has a button to confirm the change. Finally, it has a TextView at the very bottom showing a preview of what First.class' value variable is.
When a user types in "Blue" in Second.class' EditText box and hits the button, how would we change the variable from First.class without using intents and going back to that activity? I want to stay within Second.activity and do the changes from there.
After hitting the confirm button, the preview TextView should update to match the newly modified variable. We should still be seeing Second.class, I remind you. If the user hits "Back" or "up" at this point, they should return to First.class and also see that the TextView in First.class has been changed.
How do I modify First.class' variables if Second.class is entirely separate from First.class and cannot access it? (First.class is the hierarchical parent of Second.class.
Upvotes: 2
Views: 4318
Reputation: 48871
How do I modify First.class' variables if Second.class is entirely separate from First.class and cannot access it?
You can't or (more importantly) you should not try to do this.
The Android Activity
is a "special case" class and should be generally considered as being self-contained. In other words any changes to data in the second Activity
which need to be reflected in the first Activity
must be either persisted using some form of global storage (SharedPreferences
for example) or should be passed using the extras of an Intent
or a Bundle
.
With SharedPreferences
simply have the first Activity
save your currentValue
before starting the second Activity
and do the reverse in second Activity
before returning to the first. The first Activity
then simply needs to check the SharedPreferences
in onResume()
and update its TextView
if necessary.
As codeMagic mentioned, however, simply using startActivityForResult(...)
would allow passing currentValue
from the first to the second Activity
and, before the second exits, updating the Bundle
with any changes will allow it to be passed back to the first Activity
through onActivityResult(...)
.
Upvotes: 5