0

I am trying to create a preferenceScreen with this command

        PreferenceScreen screen= (PreferenceScreen)getPreferenceScreen().findPreference(KEY);

and the error message is: "inconvertible types, cannot cast android.support.v7.preference.Preference to android.preference.preferenceScreen"

Is there a way to fix it? Thanks!

Update: this is part of the testing code I wrote

        ArrayList<String> cmds = new ArrayList<String>() {{
        add("A");
        add("B");
        add("C");
    }};
    for (String cmd : cmds) {
    CheckBoxPreference cpref = new CheckBoxPreference(getActivity().getApplicationContext());
        cpref.setTitle(cmd);
        cpref.setKey("The Name");
        cpref.setChecked(true);
        cmdScr.addPreference(cpref);
    }

now the last line "addPreference" gives me an error

Deidara
  • 667
  • 2
  • 13
  • 28

1 Answers1

0

findPreference returns android.support.v7.preference.Preference and not the PreferenceScreen. What you need to do is this:

Preference screen = (Preference) getPreferenceManager().findPreference(KEY);

Where Preference is imported as the one from the support library:

import android.support.v7.preference.Preference;

To answer your edited question, just visit this link to see what you're doing wrong. Add the category to your screen, and then add the preference to the category.

Community
  • 1
  • 1
Vucko
  • 7,371
  • 2
  • 27
  • 45
  • hi @Vucko thanks for your reply. How do I import preference as the one from the support library so that the "screen" I got is a preferenceScreen? – Deidara Jun 22 '16 at 14:15
  • If you're extending `PreferenceActivity` you can use `getPreferenceManager()` instead of `getPreferenceScreen()` – Vucko Jun 22 '16 at 14:19
  • I am extending PreferenceFragmentCompat ,could you write an example please? I am kind of new to android. Thanks. – Deidara Jun 22 '16 at 14:26
  • What is your problem now dude? Is it not working? I wrote you exactly what you need. `PreferenceFragmentCompat ` has the method `getPreferenceManager()`. Use it to find the preference with the key. – Vucko Jun 22 '16 at 14:29
  • Hi Vucko I was trying to call the addPreference(screen) method after using the code you wrote. – Deidara Jun 22 '16 at 14:40
  • Did you make it work? I presume that by accepting the answer, you did? – Vucko Jun 22 '16 at 14:43
  • 1
    @Xia Edited my answer with a link that'll help you. – Vucko Jun 22 '16 at 15:11