问题
I'm getting this error in my coding and not entirely sure how to resolve this. I've searched to try and resolve this issue but can't seem to find anything that works. I've done this before but never in a fragment so maybe it could be because of that?
I'm getting following exception
:
The method getSharedPreferences(String, int) is undefined for the type 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;
} }
Could anyone please assist me with this? Any help will be appreciated!
回答1:
Change this code :
SharedPreferences pref = getSharedPreferences(PREFRENCES_NAME,0);
To :
SharedPreferences pref = getActivity().getSharedPreferences(PREFRENCES_NAME,0);
Remember you cant call getSharedPreferences
method directly from Fragment
, because it belongs to the Activity
class. Hence, you just need to call getActivity
.
回答2:
The error means that there is no getSharedPreferences method in View class, because getSharedPreferences is a method of Context class. In order to access getSharedPreferences method inside View class you need to provide it with an instance of Context class. Something like:
//Instance of Context
Context pref;
SharedPreferences sharedPref = pref.getSharedPreferences(PREFRENCES_NAME,0);
Note: Context pref & String PREFRENCES_NAME should not be null;
来源:https://stackoverflow.com/questions/26779850/how-to-resolve-an-error-getsharedpreferencesstring-int-is-undefined-for-the