Android 解決Handler在執行時載入報空指標異常
阿新 • • 發佈:2019-02-10
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);