user3383415
user3383415

Reputation: 435

Shared preferences on fragment

I am trying to use shared preferences on Android inside a fragment with appcompat. It says me to "The method getDefaultSharedPreferences(Context) in the type PreferenceManager is not applicable for the arguments (PreferenciasFragment)" Here is my code:

private void savePreferences(String key, String value) {

            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
            Editor editor = sharedPreferences.edit();
            editor.putString(key, value);
            editor.commit();

        }

Upvotes: 0

Views: 753

Answers (2)

nikis
nikis

Reputation: 11234

It happens because the argument of getDefaultSharedPreferences should have Context type (or any of it's sub-classes). The problem is you are trying to pass Fragment, but it's not a sub-class of Context. Instead, you can pass hosting Activity, which is sub-class of Context like following:

Preferences sharedPreferences = PreferenceManager
        .getDefaultSharedPreferences(getActivity());

Upvotes: 1

Hariharan
Hariharan

Reputation: 24853

Try this..

Use getActivity() instead of this

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());

Upvotes: 2

Related Questions