isValidFragment Android API 19

2019-01-08 11:14发布

When I try my app with Android KitKat I have an error in PreferenceActivity.

Subclasses of PreferenceActivity must override isValidFragment(String) to verify that the Fragment class is valid! com.crbin1.labeltodo.ActivityPreference has not checked if fragment com.crbin1.labeltodo.StockPreferenceFragment is valid

In documentation I find the following explanation

protected boolean isValidFragment (String fragmentName)

Added in API level 19

Subclasses should override this method and verify that the given fragment is a valid type to be attached to this activity. The default implementation returns true for apps built for android:targetSdkVersion older than KITKAT. For later versions, it will throw an exception.

I don't find any example to resolve the problem.

9条回答
Deceive 欺骗
2楼-- · 2019-01-08 11:57

my solution (instead of creating ArrayList of class) since the fragments that are loaded suppose to be subclass of PreferenceFragment.class run this check in the @OverRide method

@Override
protected boolean isValidFragment(String fragmentName) {
    try {
        Class cls = Class.forName(fragmentName);
        return (cls.getSuperclass().equals(PreferenceFragment.class));
                                  // true if superclass is PreferenceFragmnet
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return false;
}
查看更多
倾城 Initia
3楼-- · 2019-01-08 11:59

This API was added due to a newly discovered vulnerability. Please see http://ibm.co/1bAA8kF or http://ibm.co/IDm2Es

December 10, 2013 "We have recently disclosed a new vulnerability to the Android Security Team. [...] To be more accurate, any App which extended the PreferenceActivity class using an exported activity was automatically vulnerable. A patch has been provided in Android KitKat. If you wondered why your code is now broken, it is due to the Android KitKat patch which requires applications to override the new method, PreferenceActivity.isValidFragment, which has been added to the Android Framework." -- From the first link above

查看更多
贪生不怕死
4楼-- · 2019-01-08 11:59

I am not sure if lane's implementation is free of the vulnerabilities discussed here but if it is, then i think a better solution would be to avoid using that static list and simply do the following :

 @Override
    protected boolean isValidFragment(String fragmentName)
    {
        ArrayList<Header> target = new ArrayList<>();
        loadHeadersFromResource(R.xml.pref_headers, target);
        for (Header h : target) {
            if (fragmentName.equals(h.fragment)) return true;
        }
        return false;
    }
查看更多
登录 后发表回答