Harald Wilhelm
Harald Wilhelm

Reputation: 6716

How do I get the PreferenceManager from within BackupAgentHelper?

Within my BackupAgentHelper I need to know the name of the standard preference file. I thought "getPreferenceManager().getSharedPreferencesName()" would be a good idea but it seems that I can't get my hands on a Context.

How can I get the name of the standard preference file and/or a way to the PreferenceManager?

public class MyBackupAgentHelper extends BackupAgentHelper {

    private static final String TAG_PREFERENCES = "preferences";

    @Override
    public void onCreate() {
        SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, this
                .getPreferenceManager().getSharedPreferencesName());
        addHelper(TAG_PREFERENCES, helper);
    }
}

Upvotes: 1

Views: 628

Answers (1)

Marcin Orlowski
Marcin Orlowski

Reputation: 75645

API lacks easy way. I do that like this, to avoid hardcoding anything.

final public class BackupAgent extends BackupAgentHelper
{
    // A key to uniquely identify the set of backup data
    static final String PREFS_BACKUP_KEY = "prefs";

    public void onCreate()
    {
        String packageName = "???";
        try {
            // read current version information about this package
            Context context = getApplicationContext();
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            packageName = info.packageName;

            // preference file name is <package_name>_preferences
            packageName += "_preferences";

            SharedPreferencesBackupHelper helper = 
                            new SharedPreferencesBackupHelper(this, packageName);
            addHelper(PREFS_BACKUP_KEY, helper);

        } catch (Exception e) {
                  e.printStackTrace();
        }   
    }
}

Upvotes: 1

Related Questions