Mr.Hyde Mr.Hyde - 1 year ago 108
Android Question

How to change default name of preferences.xml database?

I want to use

getSharedPreference
instead of
getDefaultSharedPreference
( because of some bug in some devices this).

And I want to listen to preference changes. So I did something like:

this.getSharedPreferences("myPrefDB", MODE_PRIVATE).registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener()
{
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String key)
{
if (key.equalsIgnoreCase("myPrefKey"))
{
flag = sharedPreferences.getBoolean(key,true);
}
}
});


But it does not work and give me wrong preference.

Even write something like:

public class Setting extends PreferenceActivity implements OnSharedPreferenceChangeListener
{
//like above
}


Doesn't work again.

I should say I don't write anything for insert value(
edit()
,
commit()
). I just use:

addPreferencesFromResource(R.xml.preferences);


And I think this above line write the value to default database name(like "
com.example.something_preferences
"). But I want to write values to my custom name (myPrefDB).

Answer Source

To set shared preference name in PreferenceActivity, according to this:

public class SettingsActivity extends PreferenceActivity {

/*
 * (non-Javadoc)
 * 
 * @see android.preference.PreferenceActivity#onCreate(android.os.Bundle)
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getPreferenceManager().setSharedPreferencesName("myPref"); 
    addPreferencesFromResource(R.xml.pref);
}

And for use SharedPreference in every where else:

SharedPreferences prf = context.getSharedPreferences("sharedpreferenceNAMEthatYOUwant", Context.MODE_PRIVATE)

If a preferences file by this name does not exist, it will be created when you retrieve an editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download