Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SharedPreferences and PreferenceFragment

I have done the examples for PreferenceFragments and SharedPreferences on the ANdroid developer website, however I'm running into an issue now. I want to be able to access the preferences in my "Settings" screen from different Activities but I don't know what the name of the preference file generated by my preference fragment is. Does anyone know anything about specifying the preference filename for a PreferenceFragment?

like image 968
RScottCarson Avatar asked Mar 17 '13 00:03

RScottCarson


People also ask

What is the difference of SharedPreference to preference?

Differences between Preferences and Shared Preferences in Android. Preference is a package that provides classes for preferences management. Shared preferences stores data values in the XML file. This data is stored persistently in implementation- dependent backing store.

What can be stored in SharedPreferences?

Shared Preferences is the way in which one can store and retrieve small amounts of primitive data as key/value pairs to a file on the device storage such as String, int, float, Boolean that make up your preferences in an XML file inside the app on the device storage.

What is PreferenceFragment?

In Android apps, there are often settings pages that contain different options the user can tweak. The PreferenceFragment and PreferenceFragmentCompat contains a hierarchy of preference objects displayed on screen in a list. These preferences will automatically save to SharedPreferences as the user interacts with them.


1 Answers

The Preferences should be saved to the default file.

To access, use PreferenceManager#getDefaultSharedPreferences()

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences (context);

context is any valid Context, including Activities.

From the documentation on PreferenceFragment:

To retrieve an instance of SharedPreferences that the preference hierarchy in this fragment will use, call getDefaultSharedPreferences(android.content.Context) with a context in the same package as this fragment.

like image 118
A--C Avatar answered Nov 03 '22 01:11

A--C