Android 解决Handler在运行时加载报空指针异常

1.可自定义一个这样的WeakReferenceHandler

public class WeakReferenceHandler<T> extends Handler {

    private final WeakReference<T> mReference;

    public WeakReferenceHandler(T referencedObject) {
        mReference = new WeakReference<>(referencedObject);
    }

    public WeakReferenceHandler(Looper looper, T referencedObject) {
        super(looper);
        mReference = new WeakReference<>(referencedObject);
    }

    protected T getReferencedObject() {
        return mReference.get();
    }

}



 

2.在Fragment创建一个新Handler并继承WeakReferenceHandler

private RangHandler mHandler;

/**
 * 处理异步操作
 */
private static class RangHandler extends WeakReferenceHandler<RankingFragment> {

    public RangHandler(RankingFragment referencedObject) {
        super(referencedObject);
        // TODO Auto-generated constructor stub
    }

//编写自己的需要执行的任务
    @Override
    public void handleMessage(Message msg) {
        RankFragment fragment = getReferencedObject();
        if (fragment != null && fragment.getActivity() != null) {
            switch (msg.what) {
                case MSG_SHOW:
                    fragment.refreshed();
                    if (fragment.mRankDataAdapter != null) {
                        fragment.mRankDataAdapter.notifyDataSetChanged();
                    }
                    break;
                case MSG_ERROR:
                    if (fragment.isAdded())
                        Toast.makeText(fragment.getActivity(), R.string.error_response, Toast.LENGTH_SHORT).show();
                    fragment.refreshedFail();
                    break;
                default:
                    if (fragment.isAdded())
                        Toast.makeText(fragment.getActivity(), R.string.error_response, Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }
}


 
3.在onCreateView方法中实例化Handler
mHandler = new RangHandler(this);


4.需要调用的地方时
mHandler.sendEmptyMessage(MSG_SHOW);





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值