1

I have a GPS service and Settings Fragment. When Service called first time or stopped and started again by user because settings may changed I want to access values at the shared Preferences which was written by Settings Fragment.

Code at Service:

 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        setLOCATION_INTERVAL(sharedPreferences.getInt("KEY_GPS_FREQ", 1) * 1000);
        Toast.makeText(getBaseContext(), "Interval Value from SharedPref " + LOCATION_INTERVAL, Toast.LENGTH_SHORT).show();

Here, I also tried getBaseContext(). But both of them only returns 1000 this means it doesn't read correct value.

And at the Settings Fragment side here is my code:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
                editor.putInt("KEY_GPS_FREQ", seekBar.getProgress());
                editor.apply();

I also tried :

SharedPreferences preferences = getApplicationContext().getSharedPreferences("myPref",MODE_PRIVATE);

at service side and at fragment side:

SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPref",Context.MODE_PRIVATE);

they did not work too.

Ilkin
  • 386
  • 3
  • 17
  • 1
    Use PreferenceManager.getDefaultSharedPreferences(context) on both sides to access the application-level default preferences and not the Activity default preferences. – BladeCoder Jun 11 '17 at 23:22
  • @BladeCoder you are man of the day, it worked, you saved my PC`s life :D Thank's a lot – Ilkin Jun 11 '17 at 23:33

0 Answers0