Home » Android » Android preference activity IllegalArgumentException: Invalid fragment for this activity

Android preference activity IllegalArgumentException: Invalid fragment for this activity

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have a problem with my preference activity.
I’ve created to preference screens and one preference activity.
On my phone with Android 4.2.2 it works fine.
But on Android Emulator with Android 5.0 it crashes with this error: IllegalArgumentException: Invalid fragment for this activity.
Is this because of this code?:

 @Override
    protected boolean isValidFragment(String fragmentName) {
        return MyPreferenceFragment.class.getName().equals(fragmentName);
    }

The second preference fragment would be MyExportPreferenceFragment…
How can I use both of them with one activity?

Thanks for your help

//EDIT: Found a solution but maybe it’s too hacky^^

@Override
    protected boolean isValidFragment(String fragmentName) {
        if(MyPreferenceFragment.class.getName().equals(fragmentName)) {
            return MyPreferenceFragment.class.getName().equals(fragmentName);
        }
        else {
            return MyExportPreferenceFragment.class.getName().equals(fragmentName);
        }
    }

Is this okay? Or is it dangerous to do it like that?

How to&Answers:

Enumerate all the preference fragments in isValidFragment

MySettingsActivity.class

@Override
    protected boolean isValidFragment(String fragmentName) {
        return Fragment1.class.getName().equals(fragmentName) ||
                Fragment2.class.getName().equals(fragmentName) ||
                Fragment3.class.getName().equals(fragmentName) ||
                Fragment4.class.getName().equals(fragmentName) ||
                Fragment5.class.getName().equals(fragmentName);
    }

Headers.xml

<preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
    <header 
        android:title="@string/one"
        android:summary="@string/one_sum"
        android:fragment="com.***.fragment1" />
</preference-headers>

Preferences.xml

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory android:title="@string/category_basic">
        <PreferenceScreen
        android:icon="@drawable/ic_three"
        android:fragment="com.***.fragment3"
        android:title="@string/text"
        android:summary="@string/text_sum"
        android:key="@string/key" />
    </PreferenceCategory>
</PreferenceScreen>