sharedPreferences return null value

Viewed 3794

//In one Fragment

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());

SharedPreferences.Editor editor = preferences.edit();
editor.putString("aKeyString", "aValueString");
editor.apply()

//If I try to log the just saved value the log is empty. Though I thought the apply(); committed that value to memory instantly and later to disc. So should be readable ?

Log.d(TAG, preferences.getString("aKeyString",""));
//nothing is logged to logcat at all. Not even a blank line. 

However it's in another Fragment that I need to read the value but is returning null.

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
Log.d(TAG, "value: " + preferences.getString("aKeyString",""));
//Logs out "value: null"

Why is it null? I'm using getDefaultSharedPreferences which would ensure I was accessing the correct data and getActivity().getApplicationContext() for same reason.

The posts on similar issues on SO regarding preferences returning null are suggesting to use :

'apply();' instead of 'commit();' and I already am. Or they suggest to use 'getDefaultSharedPreferences' instead of 'getSharedPreferences' and again I am.

Why is it null?

3 Answers
Related