0

I have a 'SharedPreference' in my Android Application class file like this :

public class App extends Application {
    public static Context context;
    public static SharedPreferences preference;
    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        preference = PreferenceManager.getDefaultSharedPreferences(context);
   }
}

I put values to preference from a long running background service, so when I want to update my fragment content on fragment resume from this preference, in first load of activity and fragment everything is OK, but when I switch fragments, my fragment contents doesn't get updated. Please help with this.

Horizon_Net
  • 5,959
  • 4
  • 31
  • 34

2 Answers2

0

To get the instance of your preference in any fragment you can use following code.

((App)getActivity().getApplication()).preference

I can see that your preference refrence is declared as static. If there is no particular reason to keep it static you can remove the static modifier.

techierishi
  • 413
  • 3
  • 14
  • I set preference field static to access it from anywhere in my application without creating instance from App class. I want to read preference data in Background Services, Activities, Fragments and BroadcastReceivers. I am in trouble only by Fragments. – Sadjad Abbasnia Aug 11 '15 at 18:16
0

Judging by this answer Fragment onResume() not called your onResume() is not called when the fragment is swapped and recreated again.

I suggest you try to update your data in onCreateView(). You can access the shared preferences from the fragment using getActivity().getSharedPreferences(...)

Community
  • 1
  • 1
cvetanov
  • 363
  • 1
  • 3
  • 12