What is the file name used by default shared preferences?
Asked Answered
E

3

18

Android Backup Service requires a filename to backup shared preferences:

public static final String PREFS = "PrefFile";    
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);

It is clear what to use if filename is given during preferences creation like

public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);

But I use default shared preferences:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

What should I pass as PREFS value to SharedPreferencesBackupHelper?

Ehlke answered 31/10, 2014 at 12:51 Comment(0)
B
26
private static String getDefaultSharedPreferencesName(Context context) {
    return context.getPackageName() + "_preferences";
}

see your package name in AndroidManifest.xml

Bothersome answered 31/10, 2014 at 13:11 Comment(5)
Is it safe to use hardcoded value _preferences? Will it work properly on all android devices?Ehlke
It is not guaranteed. So I think it is better to use SP with defined nameBothersome
Thanks. Is there any method to get the filename from the shared preferences?Ehlke
This is now exposed as a public method on PreferenceManager in API 24: developer.android.com/reference/android/preference/…Mundford
LA_ and owner of answer - if there is no public method use Reflections - its better choice as constructing some name from code - which is changing constantly (mean api) - so - down vote for such solutionsNoranorah
C
6

From the source code, The PackageName is based on the context that you pass in.

private static String getDefaultSharedPreferencesName(Context context) {
    return context.getPackageName() + "_preferences";
}
Chamois answered 31/10, 2014 at 13:13 Comment(4)
Unfortunately, the getDefaultSharedPreferencesName method is private. Is there any public method to get it?Ehlke
Couldn't you just add this method to your code and use it that way?Chamois
As I've mentioned in the comment to another answer, I am not sure if this is the right way to hardcode it - what will happen if Google changes it in the next Android version?Ehlke
If you're worried about this changing in the next version why not just use your own key with getSharedPreferences then you won't ever have this issue. developer.android.com/training/basics/data-storage/…Chamois
D
1

The default preference file's name is the calling activity's class name.

https://developer.android.com/reference/android/app/Activity.html#getPreferences(int)

Disobey answered 17/9, 2017 at 16:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.