Android SharedPreferences in Fragment

AndroidAndroid FragmentsSharedpreferences

Android Problem Overview


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 <https://stackoverflow.com/questions/3806051/accessing-sharedpreferences-through-static-methods> and <https://stackoverflow.com/questions/6241340/static-sharedpreferences>;. Thank you for any solution.

Android Solutions


Solution 1 - Android

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);

Solution 2 - Android

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);

Solution 3 - Android

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.

Solution 4 - Android

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);
}

Solution 5 - Android

This did the trick for me

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

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

Solution 6 - Android

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();   
...   
}

Solution 7 - Android

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)...

Solution 8 - Android

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());

Solution 9 - Android

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.

Solution 10 - Android

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
     }
  }

Solution 11 - Android

use requiredactivity in fragment kotlin

 val sharedPreferences = requireActivity().getSharedPreferences(loginmasuk.LOGIN_DATA, Context.MODE_PRIVATE)

Solution 12 - Android

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");
        }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarkView Question on Stackoverflow
Solution 1 - AndroidJug6ernautView Answer on Stackoverflow
Solution 2 - AndroidLeonView Answer on Stackoverflow
Solution 3 - Androided209View Answer on Stackoverflow
Solution 4 - Androidmisbahm3View Answer on Stackoverflow
Solution 5 - AndroidAbdeljabar TaoufikallahView Answer on Stackoverflow
Solution 6 - AndroidKirguduckView Answer on Stackoverflow
Solution 7 - Androiduser11809346View Answer on Stackoverflow
Solution 8 - AndroidStanojkovicView Answer on Stackoverflow
Solution 9 - AndroidAkash VeerappanView Answer on Stackoverflow
Solution 10 - AndroiddavejoemView Answer on Stackoverflow
Solution 11 - Androidreza rahmadView Answer on Stackoverflow
Solution 12 - AndroidjayeeView Answer on Stackoverflow