Reputation: 351
I have a question about SharedPreferences
. I have implemented them in a class called HashM.java
. Starts something like this:
public void getPrefs (Context BaseContext) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(BaseContext);
I am trying to call it in my click listener this way:
HashM hash = new HashM();
hash.getPrefs();
But, I get an error:
getPrefs (Context) in HashM cannot be applied
Can someone point me to how I can fix this? thank you.
Upvotes: 0
Views: 105
Reputation: 43
If your HashM class has more methods which need a specified context, consider to make a constructor for this class with a Context parameter, and assign it to a variable, like this:
class HashM
Context mContext;
public HashM (Context context) {
mContext = context;
}
public void getPrefs () {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
And make a reference as
HashM hashM = new HashM(getActivity());
Upvotes: 1
Reputation: 4388
Adding to @Rohit5k2's answer, you can also use
HashM hash = new HashM();
hash.getPrefs(getActivity());
Upvotes: 0
Reputation: 18112
getPrefs(Context)
expects context as a parameter. You need to pass the activity context inside it.
You can do it like this
HashM hash = new HashM();
hash.getPrefs(MyActivity.this); // MyActivity is the activity where you are putting this code
Upvotes: 1