这很奇怪.我有一个简单的应用,一旦登录,该应用就会显示活动中的片段.该应用程序还具有不活动的“超时”,在此时间之后,它会完成活动并显示登录屏幕-如果该应用程序在发生超时时在后台,则在活动中发生下一个onCreate或onStart事件时,它就完成了.
但是有时返回到登录的活动时,我在片段的onActivityCreated方法中得到一个NPE.该片段非常简单,只需在String上调用一个方法.字符串本身是通过调用getArguments()来检索的.我已经验证了,无论何时创建Fragment,总是要设置参数.
因此,似乎以某种方式实际上在片段中的onCreate之前调用了onActivityCreated,我知道这是不可能的.以下是堆栈跟踪的一部分:
01-14 15:34:37.176: E/AndroidRuntime(3272): at com.example.app.fragment.MyFragment.onActivityCreated(MyFragment.java:203)
01-14 15:34:37.176: E/AndroidRuntime(3272): at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1468)
01-14 15:34:37.176: E/AndroidRuntime(3272): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:931)
01-14 15:34:37.176: E/AndroidRuntime(3272): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
01-14 15:34:37.176: E/AndroidRuntime(3272): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1070)
01-14 15:34:37.176: E/AndroidRuntime(3272): at android.support.v4.app.FragmentManagerImpl.dispatchReallyStop(FragmentManager.java:1888)
01-14 15:34:37.176: E/AndroidRuntime(3272): at android.support.v4.app.FragmentActivity.onReallyStop(FragmentActivity.java:787)
01-14 15:34:37.176: E/AndroidRuntime(3272): at android.support.v4.app.FragmentActivity.doReallyStop(FragmentActivity.java:764)
01-14 15:34:37.176: E/AndroidRuntime(3272): at android.support.v4.app.FragmentActivity.onDestroy(FragmentActivity.java:322)
01-14 15:34:37.176: E/AndroidRuntime(3272): at com.actionbarsherlock.app.SherlockFragmentActivity.onDestroy(SherlockFragmentActivity.java:261)
01-14 15:34:37.176: E/AndroidRuntime(3272): at com.example.app.MyActivity.onDestroy(MyActivity.java:195)
01-14 15:34:37.176: E/AndroidRuntime(3272): at android.app.Activity.performDestroy(Activity.java:5273)
01-14 15:34:37.176: E/AndroidRuntime(3272): at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1110)
01-14 15:34:37.176: E/AndroidRuntime(3272): at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3562)
解决方法:
经过更多调试后,我发现由于在调用onActivityCreated()之前使用了getActivity()而发生了异常-而且在getActivity()上调用了一个方法,该方法依赖于已创建的活动. /白痴