Change the Default Name of the Preferences File

Description

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;
/*from  w  w w  .  jav a  2s  . c o 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) {
    /*//from   ww  w .j  av  a  2s.  c o 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();
}




















Home »
  Android »
    Android Basics »




Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS