Search code examples
androidxmlandroid-preferencespreference

Android how to get specific preference?


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


<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<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?


Solution

  • 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