17

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?

LA_
  • 19,823
  • 58
  • 172
  • 308

3 Answers3

25
private static String getDefaultSharedPreferencesName(Context context) {
    return context.getPackageName() + "_preferences";
}

see your package name in AndroidManifest.xml

Dmitry
  • 864
  • 7
  • 15
  • Is it safe to use hardcoded value `_preferences`? Will it work properly on all android devices? – LA_ Oct 31 '14 at 13:19
  • It is not guaranteed. So I think it is better to use SP with defined name – Dmitry Oct 31 '14 at 13:24
  • 1
    Thanks. Is there any method to get the filename from the shared preferences? – LA_ Oct 31 '14 at 13:43
  • 2
    This is now exposed as a public method on `PreferenceManager` in API 24: https://developer.android.com/reference/android/preference/PreferenceManager.html#getDefaultSharedPreferencesName(android.content.Context) – Ronald Martin Jul 12 '16 at 20:34
  • 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 solutions – ceph3us Jul 31 '16 at 20:22
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";
}
MrEngineer13
  • 38,642
  • 13
  • 74
  • 93
  • Unfortunately, the `getDefaultSharedPreferencesName` method is private. Is there any public method to get it? – LA_ Oct 31 '14 at 13:44
  • Couldn't you just add this method to your code and use it that way? – MrEngineer13 Oct 31 '14 at 13:51
  • 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? – LA_ Oct 31 '14 at 14:33
  • 1
    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. http://developer.android.com/training/basics/data-storage/shared-preferences.html – MrEngineer13 Oct 31 '14 at 14:40
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)

Alastair
  • 6,837
  • 4
  • 35
  • 29