Class cast exception: cannot convert from Checkboxpreference to SwitchPreference

1.5k Views Asked by At

I am not able to identify the issue with my code and it seems no one face this kind of issue, so not able to track this in stack overflow.

Exception message:

Caused by: java.lang.ClassCastException: android.preference.CheckBoxPreference cannot be cast to android.preference.SwitchPreference

Code:

private Preference preference;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    addPreferencesFromResource(R.xml.settings);
    loadAllViews();
}

private void loadAllViews()
{
   if (VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH)
   {
        preference = (SwitchPreference) findPreference("preference"); //Exception occurs here.
   }
   else
   {
        preference = (CheckBoxPreference) findPreference("preference");
   }
}

__________________    __________________    __________________

settings.xml:

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

    <CheckBoxPreference
        android:key="preference"
        android:title="yes_or_no" />

</PreferenceScreen>

Some one please help me to figure it out.

3

There are 3 best solutions below

0
On BEST ANSWER

Need to have two separate layout.

One for check preference at layout directory.

And another for SwitchPreference at layout-v14 directory.

0
On
<?xml version="1.0" encoding="utf-8"?>

<SwitchPreference
    android:key="preference1"
    android:title="yes_or_no" />

<CheckBoxPreference
    android:key="preference2"
    android:title="yes_or_no" />

In the code:

Preference preference;

if (VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH)
{
preference = (SwitchPreference) findPreference("preference1");
}
else
{
preference = (CheckBoxPreference) findPreference("preference2");
}

3
On

CheckBoxPreference does not extends SwitchPreference; hence it cannot be cast to it. Both of these classes are children of TwoStatePreference.

From your code, it seems that you are referencing one preference key for two different preference components:

  if (VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH)
   {
        preference = (SwitchPreference) findPreference("preference"); //Exception occurs here.
   }
   else
   {
        preference = (CheckBoxPreference) findPreference("preference");
   }

As you can see, this will work fine for the correct preference type, but it will throw a ClassCastException for the incorrect type. Make sure you are referencing the correct key for the correct TwoStatePreference.