How to resolve the error: getSharedPreferences (String, int) is undefined for type new View.OnClickListener () {}
I am getting this error in my encoding and not really sure how to solve it. I have searched to try and fix this problem but cannot find anything that works. I have done this before, but have never been in a snippet, so what could be because of this?
I get the following exception
:
GetSharedPreferences (String, int) method is undefined for new View.OnClickListener () {}
Here is my code:
public class TestingFragment extends Fragment {
public TestingFragment(){}
private CheckBox ch;
private Context pref;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_testing, container, false);
ch = (CheckBox) rootView.findViewById(R.id.checkBox62);
ch.setOnClickListener(new View.OnClickListener() {
private String PREFRENCES_NAME;
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(ch.isChecked())
{
SharedPreferences pref = getSharedPreferences(PREFRENCES_NAME,0);
ch.setChecked(pref.getBoolean("cbx62_ischecked" ,true));
pref.edit().putBoolean("check",false).commit();
}
{
}}
});
return rootView;
} }
Can anyone help me with this? Any help would be appreciated!
source to share
Change this code:
SharedPreferences pref = getSharedPreferences(PREFRENCES_NAME,0);
To:
SharedPreferences pref = getActivity().getSharedPreferences(PREFRENCES_NAME,0);
Remember that you cannot call the method getSharedPreferences
directly from Fragment
, because it belongs to the class Activity
. Hence, you just need to call getActivity
.
source to share
The error means that the getSharedPreferences method is missing in the View class, because getSharedPreferences is a method of the Context class. To access the getSharedPreferences method inside the View class, you need to provide it with an instance of the Context class. Something like:
//Instance of Context
Context pref;
SharedPreferences sharedPref = pref.getSharedPreferences(PREFRENCES_NAME,0);
Note. The pref and String context PREFRENCES_NAME must not be null;
source to share