views:

83

answers:

2

I have the following code in my application in res/xml/preferences.xml:


<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"&gt;
<PreferenceCategory android:title="Wi-Fi settings">


   <EditTextPreference
            android:key="pref_voice_threshold_top"
            android:title="@string/title_pref_voicetopthreshold"
            android:dialogTitle="@string/dialog_title_pref_voicetopthreshold" 
            android:defaultValue="20"
            android:inputType="number"/>

</PreferenceCategory>

</PreferenceScreen>

And I was wondering is it possible for me to then use this preference in code so I can update it via downloading an xml file?

So I currently display the above preference in a PreferenceActivity, which works fine, however I want to be able to update the setting by downloading a new setting every week from the internet.

So my question is how do I open this preference in code and set its value to the new downloaded value?

+2  A: 

Take a look at this post in order to grab a Preference Editor object: How do I set a preference in code?

Before you get the Editor:

Parse the XML to get your desired preference values, and then use the Editor to retrieve the correct preference and subsequently set it.

McStretch
Thanks but what do I use as the String in getSharedPreferences? I have tried getSharedPreferences("pref_voice_threshold_top", 0) and getSharedPreferences("Wi-Fi settings", 0) but both return null.
Donal Rafferty
Since you're using a PreferenceActivity, you could use this method: public Preference findPreference(CharSequence key) found in PreferenceActivity.
McStretch
Sorry I wasn't clear on that part, I need to be able to set the Preference from outside the PreferenceActivity, so in this case I am not using a PreferenceActivity where I want to set the Preference
Donal Rafferty
+1  A: 

As McStretch said, you have to get the preference with

sharedPreferences = getSharedPreferences("com.yourname.yourapp_preference", 0);
Editor editor = sharedPreferences.edit();

editor.putString("your_optionname", "newValue");
// Save
editor.commit();

The com.yourname.yourapp_preference is the name of the xml file. It's typically located at /data/data/com.yourname.yourapp/shared_prefs/com.yourname.yourapp_preference.xml

Just check out that directory in to see how your file is named, but basically it should by default be packagename_perference.xml

Tseng