Hi there and welcome to StackOverflow.
The reason why you can't access SharedPreferences
is because this
is NOT the fragment: If you look closer, you'll realize that you have 2 nested contexts, so this
is really an OnClickListener
object (that is inside your fragment).
When you need to access a "parent context", you do so like this:
public class MyCoolFragment extends Fragment {
// here "this" is in fact your Fragment,
// so this.getActivity().getSharedPreferences() DOES exist
.
.
.
Button btn = (Button)findViewById(R.id.btnSave);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
// "this" is NO LONGER your fragment, but the View.OnClickListener
// to access the PARENT CONTEXT you prepend the CLASS NAME:
// MyCoolFragment.this.getActivity().getSharedPreferences will work:
SharedPreferences prefs = MyCoolFragment.this.getActivity().getSharedPreferences()
"com.example.app", Context.MODE_PRIVATE);
}
});
It is very typical in Java to have deeply-nested contexts, so you have to tell Java what this
you want.
Also, remember you can easily get the context from ANY VIEW., so inside the click handler you could also do:
Button btn = (Button)view.findViewById(R.id.btnSave);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Activity myActivity=(Activity)(v.getContext()); // all views have a reference to their context
SharedPreferences prefs =myActivity.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
}
});
Hope it helps !