How to share/pass data between activities other than Intent?

Asked

Viewed 283 times

0

I have an Android Studio application where, when clicking a button, a number is generated in Activity A and stored in another button in Activity B, which is overwritten whenever I enter a new number in Acitivty A. Is it necessary to use mysql for this or is there another method?

*I /No/ want to start Activity B every time I send the number to her. I just want to store it without having to go to the screen, but let it stay there when I wish to go.

**Please don’t be too technical as I’m still getting familiar with android studio

1 answer

1

There is no (secure) way for an Activity to "chat" directly with another Activity. The way Android is architected, different Activities and Services can be in separate processes.

If you wanted to open the other Activity, firing an Intent would be the right way. But since you don’t want to, my suggestion is to record the value generated in Activity A in the app configuration:

SharedPreferences prefs;
prefs = PreferenceManager.
        getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor ed = prefs.edit();
ed.putInt("numero", x);
ed.apply();

In Activity B you can read the configuration value:

SharedPreferences prefs;
prefs = PreferenceManager.
        getDefaultSharedPreferences(getApplicationContext());
int x = prefs.getInt("numero", defaultx);

Actiivty B can also sign up to receive notifications when the setting is changed by Activity A:

prefs.registerOnSharedPreferenceChangeListener(this);

in this case your Activity should implement an interface, and the declaration looks like:

public class ActivityB extends Activity
      implements SharedPreferences.OnSharedPreferenceChangeListener

and you must declare the method that will be called when any config changes:

public void onSharedPreferenceChanged(
         SharedPreferences sharedPreferences, String key) {
    if (key.equals("numero")) {
        ... numero mudou, atualizar o botao ....
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.