android - Use getDefaultSharedPreferences before user opens settings activity -


i have settings activity in android app. settings have default values in res/xml/preferences.xml. problem i'm having until user goes settings page, default preferences not saved , cannot retrieve default values stored in xml file.

the code:

res/xml/preferences.xml

<?xml version="1.0" encoding="utf-8"?> <preferencescreen xmlns:android="http://schemas.android.com/apk/res/android" >      <edittextpreference         android:defaultvalue="xml default value"         android:title="foo"         android:summary="bar"         android:key="mykey" />  </preferencescreen> 

settingsactivity.java

package bh.gov.cio.gdt.app;  import android.os.bundle; import android.preference.preferenceactivity; import android.preference.preferencefragment;  public class settingsactivity extends preferenceactivity {     @override     protected void oncreate(final bundle savedinstancestate) {         super.oncreate(savedinstancestate);         getfragmentmanager().begintransaction()             .replace(android.r.id.content, new mypreferencefragment()).commit();     }      public static class mypreferencefragment extends preferencefragment {         @override         public void oncreate(final bundle savedinstancestate) {             super.oncreate(savedinstancestate);             addpreferencesfromresource(r.xml.preferences);         }     } } 

inside activity:

sharedpreferences settings = preferencemanager.getdefaultsharedpreferences(this); string myvalue = settings.getstring("mykey", "code default value") log.d(log_tag, myvalue); 

the call settings.getstring returns "code default value" when application first installed. once user opens settings activity @ least once, returns xml default value.

i want avoid forcing user go settings page when program run first time. want avoid harcoding default values twice, in xml file , in code.

i believe need call in activity oncreate()

preferencemanager.setdefaultvalues(this, r.xml.advanced_preferences, false);


Comments

Popular posts from this blog

.htaccess - htaccess convert request to clean url and add slash at the end of the url -

C# random value from dictionary and tuple -

algorithm - Testing tetrahedron-triangle intersection -