3

I've got the following code for show preferences screen:

Button showPreferences=(Button)findViewById(R.id.buttonShowPreferences);
showPreferences.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
        startActivity(new Intent(MainActivity.this, PreferencesActivity.class));
    }           
});

Button logPreferences=(Button)findViewById(R.id.buttonLogPreferences);
logPreferences.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
        SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        String editText=prefs.getString("edit_text", "default_edit_text_value");
        boolean checkBox=prefs.getBoolean("check_box", true);
        String list=prefs.getString("list", "default_list_value");

        Log.i("edit_text_value", editText);
        Log.i("check_box_value", String.valueOf(checkBox));
        Log.i("list_value", list);
    }

});

As you can see the second button is used for getting values from preferences, but there is the trouble: I've got always default values from the second parameter of getString(), getBoolean() methods!

Layout for PreferenceActivity class:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:key="first_screen_key"
        android:summary="First summary"
        android:title="First title" >
        <CheckBoxPreference
            android:persistent="true"
            android:title="Check Box Title"
            android:key="check_box_key"
            android:defaultValue="false"/>
        <ListPreference 
            android:persistent="true"
            android:title="List Title"
            android:key="list_key"
            android:entries="@array/entries"
            android:defaultValue="second_value"
            android:entryValues="@array/entries_values"/>
        <EditTextPreference 
            android:persistent="true"
            android:title="Edit Text Title"
            android:key="edit_text_key"
            android:defaultValue="Edit Text Value"/>
    </PreferenceCategory>

</PreferenceScreen>
user2078683
  • 71
  • 1
  • 7

2 Answers2

1

1.you can see the xml file in DDMS->File Explorer->data->data->your package->shared_prefs->*_preferences.xml

2.replace "edit_text"/"check_box"/"list" with "check_box_key"/"list_key"/"edit_text_key".

wangqi060934
  • 1,552
  • 16
  • 23
0

The problem of your code is your key does not corresponding to your key set in the preference xml. For example, in line:

String editText=prefs.getString("edit_text", "default_edit_text_value");

but where is "edit_text" ?

In your xml, the key is named: android:key="edit_text_key" So you should replace "edit_text" with "edit_text_key"