我得到一个奇怪的NullPointerException
。我的代码中没有指向。我也知道我的应用仅在以下情况下提供此NullPointerException:
制造商:索尼爱立信
产品:MT11i_1256-3856
Android版本:2.3.4
有任何想法吗?
java.lang.NullPointerException
at android.widget.AbsListView.contentFits(AbsListView.java:722)
at android.widget.AbsListView.onTouchEvent(AbsListView.java:2430)
at android.widget.ListView.onTouchEvent(ListView.java:3447)
at android.view.View.dispatchTouchEvent(View.java:3952)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:995)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1034)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1034)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1034)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1034)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1711)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1145)
at android.app.Activity.dispatchTouchEvent(Activity.java:2096)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1695)
at android.view.ViewRoot.deliverPointerEvent(ViewRoot.java:2217)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1901)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3701)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
at dalvik.system.NativeStart.main(Native Method)
最佳答案
我的应用程序中有很多类似的异常(exception)情况。我对Android OS源代码进行了一些研究,并得出了一个结论-这是Android OS Gingerbread及以下版本的bug,并且已在Ice Cream Sandwich中修复。
如果需要更多详细信息,请在Gingerbread源代码树中查看 AbsListView.contentFits
方法的源代码:
private boolean contentFits() {
final int childCount = getChildCount();
if (childCount != mItemCount) {
return false;
}
return getChildAt(0).getTop() >= 0 && getChildAt(childCount - 1).getBottom() <= mBottom;
}
显然,如果调用此方法将为空列表,则此方法将抛出
NullPointerException
,因为getChildAt(0)
将返回NULL。此问题已在ICS source tree中修复private boolean contentFits() {
final int childCount = getChildCount();
if (childCount == 0) return true;
if (childCount != mItemCount) return false;
return getChildAt(0).getTop() >= mListPadding.top &&
getChildAt(childCount - 1).getBottom() <= getHeight() - mListPadding.bottom;
}
如您所见,检查
(childCount == 0)
。关于此问题的解决方法-您可以声明自己的类
MyListView extends ListView
,重写方法onTouchEvent
并使用try-catch块环绕super.onTouchEvent()
的调用。当然,您将需要在应用程序的所有位置使用自定义ListView类。