onCreate
onCreate

Reputation: 775

Cant create Preference in PreferenceCategory

I'm trying to create in code preference category. It works correctly. But if i try to add Preference to my category i get NullPointer Exception.

        Preference p1 = new Preference(getActivity());
        p1.setTitle("Edit name");

        PreferenceCategory prefcat = new PreferenceCategory(getActivity());
        prefcat.setTitle("title");
        prefcat.setSummary("summ");
        prefcat.addPreference(p1); // HERE I GET NULL POINTER
        ps.addPreference(prefcat);

ps - its preferencescreen object. Why? I try to debug it, Exception throws by onPrepareAddPreference method of PreferenceCategory. Hpw to fix it?

Upvotes: 2

Views: 956

Answers (1)

ozbek
ozbek

Reputation: 21183

You are trying to add a child (i.e., p1) to a parent (i.e., prefcat) which does not exist in the family (i.e., Preference) hierarchy yet.

First, add prefcat to Preference screen and then add prefcat's children. That's, reverse the order of the last two lines:

ps.addPreference(prefcat);
prefcat.addPreference(p1);

Glad it helped! :)

Upvotes: 3

Related Questions