Question

I'm trying to set the Text of a TextView in the MainActivity. The String for the Textview can be changed and set in a SettingsActivity. But somehow my code just uses the default value and doesn't read the preferences file...

greetings

Okay so I got the following

SettingsActivity.java

public class SettingsActivity extends PreferenceActivity {
    @SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }
}

preferences.xml

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <EditTextPreference
        android:capitalize="words"
        android:defaultValue="@string/default_name"
        android:inputType="textCapWords"
        android:key="Username"
        android:maxLines="1"
        android:selectAllOnFocus="true"
        android:singleLine="true"
        android:title="@string/name_button" />

</PreferenceScreen>

MainActivity.java

SettingsTest    = (TextView) findViewById(R.id.SettingsTestName);

. . .

SharedPreferences prefs = this.getSharedPreferences("preferences.xml", this.MODE_PRIVATE);
String name = prefs.getString("Username", "Username angeben");

SettingsTest.setText(name);

But for some reasons, I only get the default value "Username angeben" in the TextView...

Was it helpful?

Solution

Do something like this:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
String nickname = prefs.getString("Username", "Username angeben");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top