Java – Unable to update the header summary of PreferenceActivity on smartphones running 4.x

Unable to update the header summary of PreferenceActivity on smartphones running 4.x… here is a solution to the problem.

Unable to update the header summary of PreferenceActivity on smartphones running 4.x

As far as I know, on smartphones running 4.x, when you have a PreferenceActivity with a header, the OS will first create an Activity with a header. When a user clicks an item in the header list, another activity is created to represent the PreferenceFragment for that entry. On tablets, the title list and the fragment belong to the same activity and appear on the screen at the same time.

So, the question is this. When the user is in PreferenceFragment, he changes some settings there and I want to update the corresponding header summary. I referenced the headers object from the onBuildHeaders() call:

@Override
public void onBuildHeaders(List<Header> aTarget) {
    ...
    headers = aTarget;
}

Now to update the title, I loop through this list and check id:

private void setHeaderSummary(int id, String summary) {
    for (Header header : headers) {
        if (header.id == id) {
            header.summary = summary;
            invalidateHeaders();
            return;
        }
    }
}

This works perfectly on tablets, but not on smartphones. When the user returns from the PreferenceFragment to the first PreferenceActivity (by hitting the back button), the header remains unchanged.

Solution

I thought of a solution when typing the problem. invalidateHeaders() is called in the second activity (the activity containing the PrefenceFragment). It should be called in the initial activity (the activity that contains the header). It’s not the prettiest solution, but I keep references to parent activity and onResume(), and I’ll invalidate the header if the preference is changed.

Related Problems and Solutions