简体   繁体   English

android + sharedPreferences

[英]android + sharedPreferences

Am new to android and currently while working on Preferences, I had the following doubt, API says the following: http://developer.android.com/reference/android/content/SharedPreferences.html Modifications to the preferences must go through an SharedPreferences.Editor object to ensure the preference values remain in a consistent state API是android的新手,目前正在使用“偏好设置”时,我有以下疑问,API表示以下内容: http : //developer.android.com/reference/android/content/SharedPreferences.html对偏好设置的修改必须通过SharedPreferences .Editor对象,确保首选项值保持一致状态

But in another link , the following code style is followed: 但是在另一个链接中 ,遵循以下代码样式:


public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    if (key.equals(KEY_PREF_SYNC_CONN)) {           
        Preference connectionPref = findPreference(key);        
        connectionPref.setSummary(sharedPreferences.getString(key, ""));    
    }
}

So is it fine to edit a Preference obj without using edit and commit?? 那么在不使用edit和commit的情况下编辑Preference obj很好吗?

EDIT 编辑

EDITTED THE CODE 编辑代码

Problem was I was not able to set Default values in summary Here is the complete code that I used to fix this problem.... 问题是我无法在摘要中设置默认值这是我用来解决此问题的完整代码。

public class Settings extends PreferenceActivity implements
                OnSharedPreferenceChangeListener {      
    //initializations      
    protected void onCreate(Bundle savedInstanceState) {
     bla bla
    PreferenceManager.setDefaultValues(getBaseContext(), R.xml.preferences, false);
    addPreferencesFromResource(R.xml.preferences);
    keys = getResources().getStringArray(R.array.prefKeys);
    p = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    //Gets the keys of the preferences
    for (int i = 0; i < keys.length; i++) {
    setSummary(p, keys[i]);
    }
    }   

   //Listener to detect changes             
   public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                    String key) {
   Preference p = findPreference(key);
   if (p instanceof EditTextPreference) {
   p.setSummary(sharedPreferences.getString(key,(String) p.getSummary()));
   }
   else if (p instanceof ListPreference) {
   p.setSummary((String) ((ListPreference) p).getEntry());
   }
   }
   //First time initialization     
   private void setSummary(SharedPreferences sharedPreferences, String key) {
   Preference p = findPreference(key);
   if (p instanceof EditTextPreference) {
    //This was the mistake I did
   //p.setSummary(sharedPreferences.getString(key,(String) p.getSummary()));
   p.setSummary(((EditTextPreference) p).getText());
   }
  else if (p instanceof ListPreference) {
   //This was the mistake I did
  //p.setSummary((String) ((ListPreference) p).getEntry());         
  p.setSummary((String) ((ListPreference) p).getEntry());
  }
  }
  }

Preference and SharedPreferences are not the same. PreferenceSharedPreferences不同。 However, they are often used together. 但是,它们经常一起使用。

Preference is a UI class for displaying and editing preferences by the user. Preference是一个UI类,用于显示和编辑用户的首选项。

SharedPreferences is a non-UI class for persisting application settings. SharedPreferences是用于保留应用程序设置的非UI类。 To make changes to these settings, you obtain a SharedPreferences.Editor instance with edit() and then store the changes with commit() . 要对这些设置进行更改,请使用edit()获得一个SharedPreferences.Editor实例,然后使用commit()存储所做的更改。

Typically, Preference values are stored in SharedPreferences . 通常, Preference值存储在SharedPreferences

You are talking about two different topics there champ. 您正在谈论冠军的两个不同主题。

First, you have the SharedPreferences object, which as the guide states must and can only be edited through a SharedPreferences.Editor object. 首先,您具有SharedPreferences对象,根据指南的说明,必须并且只能通过SharedPreferences.Editor对象对其进行编辑。 See the following bit: 参见以下位:

/**
 * This function writes the user's current score to persistent storage via {@link SharedPreferences}
 * @param key The Key to store the value with, this is the same value that must be used to retrieve the preference value at a later time. 
 * @param value The Actual Value to store for the supplied key. 
 */
private void saveScore (String key, int value) {
    //First, get the instance of the SharedPreference, this is a default file that has the Package name as it's own file name. 
    SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    //Get an instance of an editor by calling .edit()
    SharedPreferences.Editor mEditor= mPreferences.edit();

    //stage the changes
    mEditor.putBoolean("your-key", true || false);
    //Call commit to persit changes
    mEditor.commit();       
}

When you talk about onSharedPreferenceChanged , that is simply an interface that allows you to know when a SharedPreference gets changes, it doesn't actually write/edit the preference file. 当您谈论onSharedPreferenceChanged ,它只是一个接口,可让您知道SharedPreference何时获得更改,它实际上并未写入/编辑首选项文件。

The onSharedPreferenceChanged interface is particuarly helpful when used alongside a PreferenceActivity or a PreferenceFragment to make changes to the User interface if needed, based on the changes to the current user preferences. onSharedPreferenceChanged接口在与PreferenceActivityPreferenceFragment结合使用时,根据当前用户首选项的更改,在必要时对用户界面进行更改时特别有用。

See this for instance: 例如看这个:

public class Settings extends PreferenceActivity {

/**
 * The Key to be used to access the preference. This should be defined already on your preferences.xml file
 */
public static final String KEY_CURRENT_THEME = "pref_current_theme";
/**
 * The instance of the Theme Preference. 
 */
Preference mThemePreference;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Find the preference
    mThemePreference = findPreference(KEY_CURRENT_THEME);
    //Set the listener
    mThemePreference.setOnPreferenceChangeListener(mOnPreferencedChanged);
    //Call onPrerenceChanged to begin with in case the settings may have changed
    //The system will call this later each time the preference gets updated by the user via Settings
    mChangeListener.onPreferenceChange(
            mThemePreference,
            PreferenceManager.getDefaultSharedPreferences(
                    mThemePreference.getContext()).getString(mThemePreference.getKey(),
                            ""));   
}

private OnPreferenceChangeListener mOnPreferencedChanged = new OnPreferenceChangeListener() {

    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        Resources mResources = preference.getContext().getResources();

        //You can check to see what change in two different ways.           
        //a) you can check the TypeOf the preference that changed. 
        if (preference instanceof CheckBoxPreference) {
            //If the preference that changes is a CheckBoxPreference, then do such and such changes. 
        } 
        //Or, you can check if it's a specific preference that changed

        if (preference == mThemePreference) {
            //If the preference is actually the Theme Preference itself, then do such and such changes. 
        }

        //Always return true so that the preference value change can be persisted, false otherwise. 
        return true;
    }
};

I hope this helps! 我希望这有帮助! :) :)

Edit 编辑

Your question: Where is the preference file stored, and how do I access it? 您的问题: 首选项文件存储在哪里,如何访问它?

Where? 哪里? The file that is created/edited via a PreferenceActivity , a PreferenceFragment or by calling PreferenceManager.getDefaultSharedPreferences(context) is stored at /data/data/your.package.name/shared_prefs/your.package.name_preferences.xml 通过PreferenceActivityPreferenceFragment或调用PreferenceManager.getDefaultSharedPreferences(context)创建/编辑的文件存储在/data/data/your.package.name/shared_prefs/your.package.name_preferences.xml中

However, where this file is stored should be irrelevant to you as a developer, since you should only access this file by making a call to PreferenceManager.getDefaultSharedPreferences(context) 但是,此文件的存储位置开发人员无关 ,因为您应通过调用PreferenceManager.getDefaultSharedPreferences(context)来访问此文件。

For instance, say you have a CheckBoxPreference that defines whether to use Holo Dark or Holo Light as your activity's theme, say, that looks something like this: 例如,假设您有一个CheckBoxPreference ,它定义是使用Holo Dark还是Holo Light作为活动的主题,例如,看起来像这样:

CheckBox首选项

Each Time the user Checks or unchecks the preference, the system will persist that change to the default preference file discussed above for you, there is no need for you to save this change manually, since it does it for you already. 每次用户选中或取消选中首选项时,系统都会持久保存更改为上面为您讨论的默认首选项文件,您无需手动保存此更改,因为它已经为您完成了。

If you want to make more than just persist the change, you can intercept the event by implementing the OnPreferenceChangeListener that I provided above, and you can even tell the system whether or not it should persist the change by returning true to persist, or false to not persist. 如果您要做的不仅仅是保留更改,还可以通过实现我上面提供的OnPreferenceChangeListener来拦截事件,甚至可以通过返回true来保留,或者返回false来告诉系统是否应保留更改。不坚持。

How to access it? 如何访问? In order to know what is the current value of the theme preference, say to actually apply UI changes based on the preference value, you can do the following: 为了知道主题首选项的当前值是什么,例如说要根据首选项值实际应用UI更改,您可以执行以下操作:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
        //We update the preference dependent values **before** setting the content view
    updatePrefDependentValues();
    setContentView(R.layout.activity_empty_container);
    }

private void updatePrefDependentValues() {
    //get the instance of the SharedPreference Object. 
    mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    //Update the boolean value based on the current preferences
    //The second parameter to getBoolean is a default value, we want false as default value. 
    mUseDarkTheme = mPreferences.getBoolean("whatever_key_you_set_for_this_preference", false);
    if (mUseDarkTheme) {
        //If we are using dark theme, set such theme. 
        setTheme(R.style.DarkTheme);
    }
    else if (!mUseDarkTheme) {
        //If we are **not** using dark theme, set light theme.
        setTheme(R.style.LightTheme);
    }
}

Let me know if you have further questions. 如果您还有其他问题,请告诉我。

Edit number three: 编辑第三:

You don't need to access the file on Eclipse, I imagine you want to open it to set default values, well, that is what the preferences.xml file is for. 您不需要在Eclipse上访问文件,我想您想打开它来设置默认值,这就是preferences.xml文件的用途。

Imagine you will have a few things on Settings, you have a CheckBoxPreference for the Theme, just as above, you have another CheckBoxPreference for enabling and disabling Background Sync, and you have a ListPreference for storing how often to sync in the background. 想象一下,您将在“设置”上有几件事,有一个主题的CheckBoxPreference ,就像上面一样,有另一个CheckBoxPreference用于启用和禁用后台同步,还有一个ListPreference用于存储后台同步的频率。

All of the above settings must be declared with a default value, in the case of a CheckBoxPreference , the default value is a boolean, either true or false, and in the case of a ListPreference the default value is whatever you want it to be, depending on the values you supply to the entries. 以上所有设置都必须声明为默认值,如果使用CheckBoxPreference ,则默认值为布尔值,是true或false;如果使用ListPreference则默认值为您想要的值,取决于您提供给条目的值。

For instance, here's a very simple preference.xml file: 例如,这是一个非常简单的preference.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Preference Categories are a good way to keep your Settings organized -->
<!-- android:key represents a String that is used to write and read from the preference file stored at /data/data/your.package.name -->
<PreferenceCategory
    android:title="@string/pref_title_general"
    android:key="pref_title_general"         
    >
    <!-- CheckBoxPreference are pretty simple, they only need a title, a key and a default value -->
    <!-- android:key is a MUST in each Preference as otherwise the system cannot persist changes to it.  -->
    <!-- android:key would be the same String you pass a "Key" 
    when calling mPreference.getBoolean(String key, Boolean default) from the Activity -->
    <CheckBoxPreference
        android:title="@string/pref_title_enable_dark_theme"
        android:key="pref_key_dark_theme"       
        android:defaultValue="false"                              
        />

</PreferenceCategory>

<PreferenceCategory
    android:title="@string/pref_title_sync_preferences"
    android:key="pref_title_navigation"         
    >

    <CheckBoxPreference
        android:title="@string/pref_title_enable_background_sync"
        android:key="pref_key_background_sync"       
        android:defaultValue="false"                              
        />

    <!-- ListPreference are a bit more complex, they require a Key to persist the changes
        android:entries represents the values displayed to the user when setting the preference
        android:entryValues represent the values that will be persisted, this array is the same size as the entries one.
        For instance, an Entry could be "Every 10 Minutes", and the entry value would be: "10" or "ten"
        This also requires a default value, which in this case MUST be a part of the entryValues array.   
        -->
    <ListPreference
        android:title="@string/pref_title_sync_frequency"
        android:key="pref_key_sync_frequency"
        android:entries="@array/pref_entries_sync_frequency"  
        android:entryValues="@array/pref_entries_values_sync_frequency" 
        android:defaultValue="@string/pref_default_sync_frequency"         
        />

</PreferenceCategory>

Again, if you use a PreferenceActivity or PreferenceFragment correctly, the changes the user makes will be persisted, and there's really nothing you should do to make the changes be there the next time the user accesses settings. 同样,如果您正确使用PreferenceActivityPreferenceFragment ,则用户所做的更改将被保留,并且实际上您无需做任何更改即可在下次用户访问设置时进行更改。

If you want to know more about Settings and Preferences, see the following: http://developer.android.com/guide/topics/ui/settings.html 如果您想了解有关设置和首选项的更多信息,请参见以下内容: http : //developer.android.com/guide/topics/ui/settings.html

Now , if what you want to do is persist other data, that may not be displayed on a PreferenceActivity or PreferenceFragment , say a user name, or an email address, then you can persisted as stated above via the saveScore example. 现在 ,如果您要保留其他数据,而这些数据可能未显示在PreferenceActivityPreferenceFragment ,例如用户名或电子邮件地址,那么您可以如上所述通过saveScore示例进行持久化。

Here's a link with more info on SharedPreferences: http://developer.android.com/training/basics/data-storage/shared-preferences.html 这是一个有关SharedPreferences的更多信息的链接: http : //developer.android.com/training/basics/data-storage/shared-preferences.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM