HelloCW
HelloCW

Reputation: 2365

The setDefaultValue for ListPreference don't work using dynamic entries

I have set lp.setDefaultValue("2"), but when I run the app, I find the 2th item isn't selected, why? Thanks!

public class PhotoPreference extends PreferenceActivity{
     @Override
     protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            addPreferencesFromResource(R.xml.mypreference);

            setContentView(R.layout.photo_preference);

            // Look up the AdView as a resource and load a request.
            AdView adView = (AdView)this.findViewById(R.id.adViewpreference);
            adView.loadAd(new AdRequest());

            ListPreference lp = (ListPreference)findPreference("SetLastFolder");            
            CharSequence[] entries = { "One", "Two", "Three" };
            CharSequence[] entryValues = { "1", "2", "3" };

            lp.setEntries(entries);
            lp.setEntryValues(entryValues);

            lp.setDefaultValue("2");      


     }

}



<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    android:key="AppPreference"
    android:summary="@string/Preferencesummary"
    android:title="@string/Preference" >   

    <ListPreference    
        android:key="SetLastFolder"
        android:dialogTitle="@string/SelectGallery"
        android:title="@string/SelectGallery"
        android:summary="@string/SelectGallerysummary"        
        android:layout="@layout/photopreference_layout" 
     />

</PreferenceScreen>

Upvotes: 1

Views: 433

Answers (1)

neo108
neo108

Reputation: 5264

Try setValueIndex() instead of setDefaultValue().

See this question

So if you change...

lp.setDefaultValue("2");

to...

lp.setValueIndex(int index); // pass the appropriate index

then it should work.

Updated
I hope defaultvalue is locate the index 1 only when a user have not do any choice!

For this, you can check if lp is null first and then set the defaultvalue...

if(lp.getValue() == null) {
   lp.setValueIndex(1);
}

Upvotes: 4

Related Questions