androidpreferenceactivitycheckboxpreference

Class cast exception: cannot convert from Checkboxpreference to SwitchPreference


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.


Solution

  • Need to have two separate layout.

    One for check preference at layout directory.

    And another for SwitchPreference at layout-v14 directory.