I want to save a preference so that I can access it from all classes within my app. But it should not be accessible from outside my app, since it will contain user login data.
In the Android documentation it was my understanding that MODE_PRIVATE
should do it. But if I use MODE_PRIVATE I can only access the preference from within the class where I created it.
Class1.java:
....
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editPrefs = prefs.edit();
editPrefs.putString("myPref", "myValue");
editPrefs.commit();
...
Class2.java:
...
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String myString = prefs.getString("myPref", " ");
...
If I call getString
within the same class where I created it, then it returns myValue
(even after closing the app, and without putting it again).
If I call getString
in another class within the same app, then it returns " ".
Thanks!
Try this:
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
For documentation see: http://developer.android.com/reference/android/preference/PreferenceManager.html#getDefaultSharedPreferences(android.content.Context)