Search code examples
javaandroidsharedpreferences

Can't get string from sharedPreferences in Fragment


I'm an experienced Android Developer (Kotlin) and I'm currently working on a Java app and I can't manage to get a simple string from shared preferences.

This is my code

LoginActivity.java

public static final String USERNAME_KEY = "currentusername";

        vialApp.loginAsync(emailPasswordCredentials, it -> {
            // re-enable the buttons after user login returns a result
            binding.buttonLogin.setEnabled(true);
            binding.buttonCreate.setEnabled(true);
            if (!it.isSuccess()) {
                onLoginFailed(it.getError().getErrorMessage());
            } else {
                SharedPreferences pref = this.getPreferences(Context.MODE_PRIVATE);
                SharedPreferences.Editor edt = pref.edit();
                edt.putString(USERNAME_KEY, username);
                edt.apply();
                onLoginSuccess();
            }
        });

This is saving correctly, if I try to get the prefs in this activity the same way as I do in the Fragment, it gets the username. This activity navigates to a home fragment and then to the fragment that gets the String.

However, in the fragment:

private void getCurrentUsername() { // Called from OnViewCreated()
    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    String user = sharedPref.getString(LoginActivity.USERNAME_KEY, "username"); // NEED FIX
    binding.profilePicUsername.setText("Hello " + user + "!");
}

I tried everything I found here, using PreferenceManager.getDefaultSharedPreferences, getSharedPreferences, using context instead of activity. Nothing works.


Solution

  • You should use this reference to PreferenceManager into the Activity:

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

    ... and the following one into the fragment:

    private SharedPreferences preferences;
    preferences = PreferenceManager.getDefaultSharedPreferences(getContext());