I am trying to read SharedPreferences inside Fragment. My code is what I use to get preferences in any other Activity.
SharedPreferences preferences = g
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
}
}
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());
use requiredactivity in fragment kotlin
val sharedPreferences = requireActivity().getSharedPreferences(loginmasuk.LOGIN_DATA, Context.MODE_PRIVATE)
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);
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)...
This did the trick for me
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
Check here https://developer.android.com/guide/topics/ui/settings.html#ReadingPrefs