Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

android - What's the difference between getDefaultSharedPreferences() and getPreferences()?

I'm currently taking the "Developing Android Apps" Udacity course. In the "Lesson 3: New Activities and Intents > Use SharedPreferences" segment, the instructor asked me to dig around the Android Developer site for how to get the user preferences from SharedPreferences. However, I found it different between the official documentation and the course's solution.

The Udacity course's solution says, to grab a SharedPreferences instance for the PreferenceActivity, you should call:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());

(where getActivity() is simply the Context here because it's called inside a Fragment.)

While the official documentation on Android Developer Site indicates that you should call:

SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE)

So what's the difference between PreferenceManager.getDefaultSharedPreferences(Context context) and Activity.getPreferences(int mode)?

Please note: This question does not involve anything about getSharedPreferences() which requires a file name. It's about the difference between getPreferences() and getDefaultSharedPreferences().

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Acoording to the link you provided to Android documentation

getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.

getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.

So it is, use getSharedPreferences when the data you want to save/retrieve can be used from different activities in the app. If those preferences will only be used in one Activity, you can use getPreferences.

Edit: also note that as said in the post you linked 'getDefaultSharedPreferences will use a default name like "com.example.something_preferences", but getSharedPreferences will require a name'


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...