android.app.fragment instantiationexception,Fragment子类如果没有无参数构造器,可能导致某些情况下抛出异常InstantiationException...

碰到一个很难复现的crash,LogCat捕捉到如下crash信息:

android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment MyFragment: make sure class name exists, is public, and has an empty constructor that is public

从Fragment文档中看到可能与此crash相关的说明:

译:所有Fragment子类必须要包含无参数构造器。Framework在必要时候常常需要重新实例化一个fragment,尤其在恢复fragment状态时,需要能找到这个构造器。如果找不到,在上述提到的情况下就会抛出运行时异常。

原文:All subclasses of Fragment must include a public no-argument constructor. The framework will often re-instantiate a fragment class when needed, in particular during state restore, and needs to be able to find this constructor to instantiate it. If the no-argument constructor is not available, a runtime exception will occur in some cases during state restore.

因为我偏向于使用如下方法实例化Fragment,所以代码中就没再定义构造器:

public static MyFragment newInstance(Date date) {

Log.d(TAG, "newInstance");

Bundle args = new Bundle();

args.putLong(EXTRA_DATE, date.getTime());

MyFragment fragment = new MyFragment();

fragment.setArguments(args);

return fragment;

}

为了解决crash,以及保险起见,就添加了一个空的构造器:

public MyFragment() {

super();

}

因为crash很难复现,所以并不能确定是否有用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值