0

I have an app using fragments. One of which is a PreferenceFragment, and those are all in the package "fragments".

I load up the settings fragment and can see the options, change values, and all is saved.

fragmentPrefsCurrentView fragment

public class fragmentPrefsCurrentView extends PreferenceFragment {

 @Override
    public void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.prefs);

        //test
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        boolean b = prefs.getBoolean("applicationOptionOne", false);

    }
}

The b boolean test returns the correct value.

R.xml.prefs XML file:

<PreferenceCategory
    android:title="@string/sectionname">

    <SwitchPreference android:title="Bases"
        android:defaultValue="true"
        android:key="applicationOptionOne" />

</PreferenceCategory>

Now, in another class, which is also a fragment and in the same package/folder, I am trying to access these same values but the returned value is always an empty map.

fragmentMap fragment

public class fragmentMap extends Fragment {



   @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {

        prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        boolean b = prefs.getBoolean("applicationOptionOne", false);

        super.onActivityCreated(savedInstanceState);
    }
}

I thought maybe it's something to do with a wrong context or scope, or perhaps the preferences aren't being loaded at the point I'm trying to access them in the second fragment?

1) preferences fragment loaded up - prefs contains the correct mMap 2) fragmentMap loaded up - prefs contains empty mMap

Any thoughts? Cheers.

Jammo
  • 1,838
  • 4
  • 25
  • 39
  • Where are you saving the preferences? – Ankur Kumar Sep 08 '15 at 10:44
  • Buit from the xml file `addPreferencesFromResource(R.xml.prefs);` – Jammo Sep 08 '15 at 10:46
  • you are using deprecated method `addPreferencesFromResource(R.xml.prefs)` try creating preferences as shown in this so thread http://stackoverflow.com/questions/23523806/how-do-you-create-preference-activity-and-preference-fragment-on-android – karan Sep 08 '15 at 10:54
  • I didn't realise it was deprecated. Bit confused though. The link you pasted has solutions that still use `addPreferencesFromResource(R.xml.fragment_preference);` – Jammo Sep 08 '15 at 11:19
  • *bump* Anyone else able to shed some light? – Jammo Sep 08 '15 at 16:46
  • After much searching I've found that actually, `addPreferencesFromResource` for **PreferenceActivity** is deprecated but for **PreferenceFragment** is still ok to use. Still have my original problem accessing these settings – Jammo Sep 09 '15 at 11:57

0 Answers0