Tell me this question: class B stores data in SharedPreferences :

 public SharedPreferences mPreferencesregistr = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPreferencesregistr = getSharedPreferences("firstrun", Context.MODE_PRIVATE); if (!issaveFiiled()) { mPreferencesregistr.edit().putBoolean("firstrun", true).apply(); SaveData.this.finish(); } } 

in class A you need to check:

 if (mPreferencesregistr.getBoolean("firstrun", false)) { uploadImage(); } else{//условие} 

How to get the value of the variable mPreferencesregistr if mPreferencesregistr in another class

  • one
    Just in another activity, get a new copy of SharedPreferences with the same parameters ( mPreferencesregistr = getSharedPreferences("firstrun", Context.MODE_PRIVATE); ) and access it. - pavlofff

2 answers 2

Store the settings in the PreferenceManager.getDefaultSharedPreferences(context); . They will be available to you throughout the application.

 preferences = PreferenceManager.getDefaultSharedPreferences(context); preferences.getBoolean("firstrun", false) 

and put there like this:

 SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);; Editor ed = pref.edit(); ed.putBoolean("firstrun", true); ed.apply(); 
  • and how to put mPreferencesregistr.edit().putBoolean("firstrun", true).apply(); ? - upward
  • Added in response a description of how to put data there - pavel163

A good option is to make Singleton the PreferencesManager class, which describes all interactions with SharedPreferences.

 public class PreferencesManager { private SharedPreferences sharedPreferences; private static PreferencesManager INSTANCE = null; private final String USER_TOKEN_KEY = "USER_TOKEN_KEY"; private PreferencesManager(Context context) { this.sharedPreferences = context.getSharedPreferences("com.myappcompany.myapp", Context.MODE_PRIVATE); } public static PreferencesManager getInstance(Context context) { if (INSTANCE == null) { synchronized (PreferencesManager.class) { if (INSTANCE == null) { INSTANCE = new PreferencesManager(context); } } } return INSTANCE; } public void saveToken(String token) { sharedPreferences.edit().putString(this.USER_TOKEN_KEY, token).commit(); } public String getToken() { return sharedPreferences.getString(this.USER_TOKEN_KEY, "empty"); } } 

Accordingly, we get access to the object in any activity as follows:

 PreferencesManager preferencesManager = PreferencesManager.getInstance(context); 

And we turn to the methods that interest us:

  //Допустим, хотим проверить токен и, //если новый токен не равен старому, сохраним новый String newToken; if (preferencesManager.getToken().equals(newToken)) { preferencesManager.saveToken(newToken); } 
  • one
    But why do this if any instance of SharedPreference with the same parameters gets access to the same settings file? - pavlofff