在用到FragmentPagerAdapter的时候,出现了下面的错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Handler android.support.v4.app.FragmentHostCallback.getHandler()' on a null object reference
看到这个,瞬间懵逼了,于是在网上怒搜,没想到,好多人都碰到了这个问题,原来这个是Google support library的问题,而且一直没有解决:
#3 nksa...@gmail.com
This is also bug too on 24.1.1
Aug 3, 2016#4 rfml...@gmail.com
Any workaround anyone?
Aug 6, 2016#5 chernand...@gmail.com
I am having the same error
Nexus 5, android 6.0.1, support library 24.0.0.
Aug 11, 2016#6 christi...@carezone.com
Probably related to https://code.google.com/p/android/issues/detail?id=208911
Aug 12, 2016#7 ffvander...@gmail.com
and to https://code.google.com/p/android/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Status%20Priority%20Owner%20Summary%20Stars%20Reporter%20Opened&groupby=&sort=&id=218912
Aug 12, 2016Project Member #8 amruthav...@google.com
(No comment was entered for this change.)
Status: Duplicate
Owner: amruthav...@google.com
Mergedinto: 218912
Aug 18, 2016#9 fernando...@gmail.com
Still around in 'com.android.support:support-v4:24.2.0'
Does anyone has any workaround for this?
Thanks!
Aug 22, 2016#10 meghal.s...@teamaol.com
This story has been merged into https://code.google.com/p/android/issues/detail?id=218912
Sep 26, 2016#12 rfml...@gmail.com
Still around in 'com.android.support:support-v4:24.2.1'
Does anyone got any workaround for this?
可以看出,各种人吐槽,而且google一直没有修复,也没有打算修复的想法,最后一个人直接这样质问Google的开发者,也是够直接,够犀利:
#14 nksa...@gmail.com
Googlers it is shame that the bug is there in view pager more than 3 years. Why don't you take seriously? Fix it guys can't wait more time
没办法,我也是各种搜索,最后总算找到了一种解决办法,但是具体出处忘了,这里感谢一下!
在你的FragmentPagerAdapter代码下,复写finishUpdate方法:
@Override
public void finishUpdate(ViewGroup container) {
try{
super.finishUpdate(container);
} catch (NullPointerException nullPointerException){
Log.d("Catch the NullPointerException in FragmentPagerAdapter.finishUpdate");
}
}
当然,因为我是在异步线程之后调用notifyDataSetChanged刷新adapter的,所以也可以在刷新之前判断viewpager的状态:
if (viewPager == null || isDetached()) return;