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

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

public class WeakReferenceHandler extends Handler {

    private final WeakReference 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 {

    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);





你可能感兴趣的:(Android,Android,Fragment,Handler)