Mark
Mark

Reputation: 1073

Android SharedPreferences in Fragment

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.

Upvotes: 101

Views: 167814

Answers (12)

jayee
jayee

Reputation: 9

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

Upvotes: 0

Akash Veerappan
Akash Veerappan

Reputation: 76

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.

Upvotes: 2

reza rahmad
reza rahmad

Reputation: 1049

use requiredactivity in fragment kotlin

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

Upvotes: 0

Stanojkovic
Stanojkovic

Reputation: 1632

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

Upvotes: 2

davejoem
davejoem

Reputation: 5482

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

Upvotes: 0

user11809346
user11809346

Reputation: 11

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

Upvotes: 1

Kirguduck
Kirguduck

Reputation: 796

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

Upvotes: 1

Leon
Leon

Reputation: 3726

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

Upvotes: 21

This did the trick for me

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

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

Upvotes: 2

misbahm3
misbahm3

Reputation: 101

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

Upvotes: 4

Jug6ernaut
Jug6ernaut

Reputation: 8325

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

Upvotes: 283

ed209
ed209

Reputation: 838

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.

Upvotes: 9

Related Questions