SharedPreferences methods not found

1

I can not save using SharedPreferences , Android Studio accuses methods do not exist.

By the official SharedPreferences documentation has the 2 forms, as needed from where find the value:

Calling any context ( getSharedPreferences() ):

Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
        getString(R.string.preference_file_key), Context.MODE_PRIVATE);

Calling a certain context ( getPreferences() ):

SharedPreferences sharedPref = 
     getActivity().getPreferences(Context.MODE_PRIVATE);

But regardless of which one I try to use, none is recognized.

I tested in extended class of AppCompatActivity , and AsyncTask (which is where I need to use).

    
asked by anonymous 15.02.2018 / 19:50

1 answer

1

Try to use getDefaultSharedPreferences(Context) , this form uses a default file defined for the app, so any class that has access to the application context will be able to use this method.

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);

To use AsyncTask, get the outside context.

    
16.02.2018 / 01:49