Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't i add first header to getPreferenceScreen?

Tags:

java

android

The standard settings activity from google android studio is now showing the first header "General". So i modified the code but i get java.lang.NullPointerException at first occurrence of getPreferenceScreen().addPreference(fakeHeader);

private void setupSimplePreferencesScreen() {
    if (!isSimplePreferences(this)) {
        return;
    }


    PreferenceCategory fakeHeader = new PreferenceCategory(this);
    fakeHeader.setTitle(R.string.pref_header_notifications);
    getPreferenceScreen().addPreference(fakeHeader);
    addPreferencesFromResource(R.xml.pref_general);



      fakeHeader = new PreferenceCategory(this);
    fakeHeader.setTitle(R.string.pref_header_notifications);
    getPreferenceScreen().addPreference(fakeHeader);
    addPreferencesFromResource(R.xml.pref_notification);

    bindPreferenceSummaryToValue(findPreference("username"));
    bindPreferenceSummaryToValue(findPreference("password"));
    bindPreferenceSummaryToValue(findPreference("server"));

}

    @Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
    if (!isSimplePreferences(this)) {
        loadHeadersFromResource(R.xml.pref_headers, target);
    }
}

<header
    android:fragment="com.example.eslam.rottapharm.SettingsActivity$GeneralPreferenceFragment"
    android:title="@string/pref_header_general" />
</preference-headers>
like image 916
Eslam Sameh Ahmed Avatar asked Jul 13 '14 00:07

Eslam Sameh Ahmed


1 Answers

OK, I figured it out because it was annoying to me as well. So in order to display the header title for the first preference section (e.g. general), I added another xml file (PreferenceScreen) which is used as a container. I called it pref_container.xml and it is located in xml directory along with other preference headers like pref_general.xml, pref_notification.xml, etc. The code in it:

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

Then, in the SettingsActivity.java I have:

// Add container
addPreferencesFromResource(R.xml.pref_container);

// Add 'general' preferences, and a corresponding header.
PreferenceCategory fakeHeader = new PreferenceCategory(this);
fakeHeader.setTitle(R.string.pref_header_general);
getPreferenceScreen().addPreference(fakeHeader);
addPreferencesFromResource(R.xml.pref_general);

// Add 'backup' preferences, and a corresponding header.
fakeHeader = new PreferenceCategory(this);
fakeHeader.setTitle(R.string.pref_header_backup);
getPreferenceScreen().addPreference(fakeHeader);
addPreferencesFromResource(R.xml.pref_backup);

This does the trick for me.

like image 182
marius Avatar answered Nov 14 '22 23:11

marius