FragmentActivity with ViewPager: Crash on orientation change

南楼画角 提交于 2019-12-01 05:24:29

There's a couple of hints on the following lines:

Caused by: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.walletv2.activity.PayeeListActivity$PayeeListSectionFragment: make sure class name exists, is public, and has an empty constructor that is public

And:

06-07 11:01:57.834: E/AndroidRuntime(766): Caused by: java.lang.InstantiationException: can't instantiate class com.walletv2.activity.PayeeListActivity$PayeeListSectionFragment; no empty constructor

That suggests that you've added a parameterized constructor to your PayeeListSectionFragment inner class. Unfortunately, that won't work, as Android relies on invoking a non-parameterized constructor using reflection in order to restore a fragment's state on configuration changes (amongst other things).

If you want to supply one or more parameters to a fragment, you'll have to plug them into a Bundle and set it as argument, using setArguments(Bundle). Have a look at the DetailsFragment and CountingFragment in the documentation for an example on how to do that.


This problem can also arise in another situation, which may be less obvious for those not too familiar with Java. If your fragment is a nested class of say some Activity, make sure you declare the inner class static. For example, in the context of above question, it should be a public static class PayeeListSectionFragment (with an emphasis on the static modifier). That way the inner class won't keep a reference to the outer class and can have its own life cycle, without any dependencies on the outer class. Without the static modifier, the nested class can't be instantiated without instantiating the outer class, which means Android will run into issues when attempting to reinstantiate your fragment class.

An alternative solution would be to move the inner class to its own .java file. That way any outer class dependencies are automatically removed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!