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

前端 未结 4 1944
挽巷
挽巷 2020-12-09 18:54

I\'m currently taking the \"Developing Android Apps\" Udacity course. In the \"Lesson 3: New Activities and Intents > Use SharedPreferences\" segment, the instructor asked

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-09 19:15

    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'

提交回复
热议问题