101

I am trying to read SharedPreferences inside Fragment. My code is what I use to get preferences in any other Activity.

     SharedPreferences preferences = getSharedPreferences("pref", 0);

I get error

    Cannot make a static reference to the non-static method getSharedPreferences(String, int) from the type ContextWrapper    

I have tried to follow these links but with no luck Accessing SharedPreferences through static methods and Static SharedPreferences. Thank you for any solution.

Community
  • 1
  • 1
Mark
  • 1,073
  • 2
  • 10
  • 9

12 Answers12

279

The method getSharedPreferences is a method of the Context object, so just calling getSharedPreferences from a Fragment will not work...because it is not a Context! (Activity is an extension of Context, so we can call getSharedPreferences from it).

So you have to get your applications Context by

// this = your fragment
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
Jug6ernaut
  • 8,219
  • 2
  • 26
  • 26
  • 1
    getSharedPreferences("pref",0); zero(0) means what private/public? – Kailas Oct 22 '13 at 07:25
  • @Kailas correct, the mode, ie WORLD_READABLE ect. http://developer.android.com/reference/android/content/Context.html#getSharedPreferences(java.lang.String, int) – Jug6ernaut Oct 22 '13 at 22:25
  • what type of mode i used the shared preferences only access by that application none other application read/write that shared preferences values? – Kailas Oct 23 '13 at 06:55
  • 5
    0 is analogous to MODE_PRIVATE (or Context.MODE_PRIVATE if used within a class that isn't an extension of Context, such as a Fragment). It means only the app in question can access the preferences. You shouldn't use WORLD_READABLE or WORLD_WRITEABLE as they are deprecated in API 17+, not to mention a security threat. – Ankit Aggarwal Jan 02 '14 at 05:15
  • 1
    is this `this` keyword necessary when doing `this.getActivity().getShared..`? – Subby Jan 16 '14 at 13:01
  • 3
    @Subby no, explicitly calling just "this" is never necessary. I did it out of personal preference as i hate ambiguous method calls. The only time "this" is required is when you are trying to access a parent non static object when you are out of its scope being in an anonymous inner class/interface. – Jug6ernaut Jan 17 '14 at 13:57
  • Only the simple trick is "Don't declare the SharedPreferences below the curly bracket of the fragment class ". I just used it inside the " onViewCreated " method and worked for me. – user7418129 Apr 02 '20 at 18:32
20

The marked answer didn't work for me, I had to use

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

EDIT:

Or just try removing the this:

SharedPreferences prefs = getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
Leon
  • 3,614
  • 1
  • 33
  • 46
  • 8
    The marked answer didn't work for you because you are accessing default shared preferences. A better design is to store your preferences not as a shared object but in a separate and private space, which is what the question and answer is about here. – zeeshan Nov 10 '14 at 15:48
8

As a note of caution this answer provided by the user above me is correct.

SharedPreferences preferences = this.getActivity().getSharedPreferences("pref",0);

However, if you attempt to get anything in the fragment before onAttach is called getActivity() will return null.

ed209
  • 828
  • 2
  • 14
  • 30
4

You can make the SharedPrefences in onAttach method of fragment like this:

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    SharedPreferences preferences = context.getSharedPreferences("pref", 0);
}
misbahm3
  • 101
  • 5
2

This did the trick for me

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

Check here https://developer.android.com/guide/topics/ui/settings.html#ReadingPrefs

2

Given a fragment, you can setup your SharedPreferences like so:

val sharedPreferences = activity!!.applicationContext.getSharedPreferences(TAG,   Context.MODE_PRIVATE) // kotlin
SharedPreferences sharedPreferences = getActivity().getApplicationContext().getSharedPreferences(TAG,   Context.MODE_PRIVATE); // java

Let me know if you have any further questions.

Akash Veerappan
  • 76
  • 1
  • 1
  • 6
1

getActivity() and onAttach() didnot help me in same situation
maybe I did something wrong
but! I found another decision
I have created a field Context thisContext inside my Fragment
And got a current context from method onCreateView
and now I can work with shared pref from fragment

public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {   
...   
thisContext = container.getContext();   
...   
}
Kirguduck
  • 748
  • 1
  • 9
  • 20
1

To define the preference in Fragment: SharedPreferences pref = getActivity().getSharedPreferences("CargaDatosCR",Context.MODE_PRIVATE); editor.putString("credi_credito",cre); editor.commit();

To call another activity or fragment the preference data: SharedPreferences pref = getActivity().getSharedPreferences("CargaDatosCR", Context.MODE_PRIVATE); credit=pref.getString("credi_credito",""); if(credit.isNotEmpty)...

AlexPad
  • 10,364
  • 3
  • 38
  • 48
1

Maybe this is helpfull to someone after few years. New way, on Androidx, of getting SharedPreferences() inside fragment is to implement into gradle dependencies

implementation "androidx.preference:preference:1.1.1"

and then, inside fragment call

SharedPreferences preferences;
preferences = androidx.preference.PreferenceManager.getDefaultSharedPreferences(getActivity());
Stanojkovic
  • 1,612
  • 1
  • 17
  • 24
0

It is possible to get a context from within a Fragment

Just do

public class YourFragment extends Fragment {

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        final View root = inflater.inflate(R.layout.yout_fragment_layout, container, false);
        // get context here
        Context context = getContext();
        // do as you please with the context


        // if you decide to go with second option
        SomeViewModel someViewModel = ViewModelProviders.of(this).get(SomeViewModel.class);
        Context context = homeViewModel.getContext();
        // do as you please with the context
        return root;
    }
}

You may also attached an AndroidViewModel in the onCreateView method that implements a method that returns the application context

public class SomeViewModel extends AndroidViewModel {

    private MutableLiveData<ArrayList<String>> someMutableData;
    Context context;

    public SomeViewModel(Application application) {
        super(application);
        context = getApplication().getApplicationContext();
        someMutableData = new MutableLiveData<>();
        .
        .
     }

     public Context getContext() {
         return context
     }
  }
davejoem
  • 4,902
  • 4
  • 22
  • 31
0

use requiredactivity in fragment kotlin

 val sharedPreferences = requireActivity().getSharedPreferences(loginmasuk.LOGIN_DATA, Context.MODE_PRIVATE)
reza rahmad
  • 1,009
  • 10
  • 16
0

Get Current Date and Time or get each every attributes from it:

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;

String timeStamp = new SimpleDateFormat( "dd/MM/yy   HH:mm:ss").format(Calendar.getInstance().getTime());

        String timeStamp1 = new SimpleDateFormat("dd/MM/yy").format(Calendar.getInstance().getTime());
        String timeStamp2 = new SimpleDateFormat("dd").format(Calendar.getInstance().getTime());
        System.out.print(timeStamp1);
        if(timeStamp1.contains("10/03/21")) {
            System.out.print("\ntrue");
        }
        else {
            System.out.print("false");
        }
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
jayee
  • 9
  • 1