Clo Knibbe Clo Knibbe - 6 days ago 7
Android Question

test suite not overwrite DefaultSharedPreferences

I am using the SettingsActivity created by AndroidStudio (extends AppCompatPreferenceActivity, which extends PreferenceActivity). My preference values are getting stored in the DefaultSharedPreferences (pkg-name_preferences.xml).

I'd like to be able to specify a different name for the DefaultSharedPreference file when the test suite is running. This would prevent the test suite from over-writing any preference values I may have set during normal use of the app.

Is it possible to do this? (Just to be clear: I am able to detect if the test suite is running, but I don't know how to specify a name for the DefaultSharedPreferences.)

I found some old posts that suggest:

PreferenceManager prefMngr = getPreferenceManager();
prefMngr.setSharedPreferencesName("my_name");


getPreferenceManager() was deprecated in API 11, and if I try to use it anyway it returns null.

Or maybe there is some other way to achieve my objective (test suite not over-writing app's preference values)?

Answer

I figured it out.

The boiler-plate SettingsActivity includes inner classes for each sample preference group (for example, GeneralPreferenceFragment). These classes extend PreferenceFragment.

I added a class that extends PreferenceFragment and specifies a name for the preference file:

/**
 * This (abstract) fragment is a super-class for the category-specific fragments.
 * It sets the shared preferences file name.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
abstract private static class MyPreferenceFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // set the shared preferences file name
        getPreferenceManager().setSharedPreferencesName("my file name");
    }
}

I changed GeneralPreferenceFragment (and the 2 other inner classes) to extend MyPreferenceFragment, rather than PreferenceFragment.