Android How to - Change the Default Name of the Preferences File








The default name of the preferences file saved on the device is com.java2s..., with the package name used as the prefix.

The following code shows how to Change the Default Name of the Preferences File.

Example

We can use the following code to change the name of preferences file.

package com.java2s.myapplication3.app;
/*  w ww  .ja va  2s  .  co  m*/
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;

public class MainActivity extends PreferenceActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        PreferenceManager prefMgr = getPreferenceManager();
        prefMgr.setSharedPreferencesName("appPreferences");

        //load the preferences from an XML file
        addPreferencesFromResource(R.xml.myapppreferences);
    }
}

Code to read the preference.

public void onClickDisplay(View view) {
    /*/*  w  ww .  ja  v a2 s.co m*/
    SharedPreferences appPrefs =
            getSharedPreferences("com.java2s.UsingPreferences_preferences",
                    MODE_PRIVATE);
    */
    SharedPreferences appPrefs =
            getSharedPreferences("appPreferences", MODE_PRIVATE);

    DisplayText(appPrefs.getString("editTextPref", ""));
}

public void onClickModify(View view) {
    /*
    SharedPreferences appPrefs =
            getSharedPreferences("com.java2s.UsingPreferences_preferences",
                    MODE_PRIVATE);
    */
    SharedPreferences appPrefs =
            getSharedPreferences("appPreferences", MODE_PRIVATE);

    SharedPreferences.Editor prefsEditor = appPrefs.edit();
    prefsEditor.putString("editTextPref",
            ((EditText) findViewById(R.id.txtString)).getText().toString());
    prefsEditor.commit();
}