我在一个活动的ViewPager中有4个片段。在其中一个片段中,我为结果启动了一个活动,并且在返回第一个活动时总是会崩溃。错误是:
Process: com.mycom.android.myapp.debug, PID: 13505
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=196610, result=0, data=Intent { }} to activity {com.mycom.android.myapp.debug/com.mycom.android.myapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.Fragment.onActivityResult(int, int, android.content.Intent)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3539)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582)
at android.app.ActivityThread.access$1300(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.Fragment.onActivityResult(int, int, android.content.Intent)' on a null object reference
at com.mycom.android.myapp.fragment.AgendaFragment.onActivityResult(AgendaFragment.java:415)
虽然我尝试评论片段的onActivityResult函数的主体,但仍然会发生。看起来片段没有及时恢复。
我该如何处理这件事? TKS
更新:这是问题片段中的onActivityResult。有子片段,我确信这些片段中也有@Override。我尝试评论循环的主体,仍然没有运气。还有什么想法吗?感谢。
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
LOGD(TAG, "onActivityResult called BEFORE calling super");
super.onActivityResult(requestCode, resultCode, data);
LOGD(TAG, "onActivityResult called AFTER calling super");
/**we need to broadcast this event to nested child fragments */
List<Fragment> fragments = getChildFragmentManager().getFragments();
if (!CollectionUtils.isEmpty(fragments)) {
for (Fragment fragment : fragments) {
if(fragment!=null){
LOGD(TAG, "fragment not null");
fragment.onActivityResult(requestCode, resultCode, data);
}else
LOGD(TAG,"fragment IS null");
}
}
}
更新2 :因为我在一个嵌套的AgendaFragment片段中的startActivity(),跟随pvshnik在onActivityResult() not called in new nested fragment API的回答
在ListFragment
里面,这是一个AgendaFragment的子片段,我做了
getParentFragment().startActivityForResult(intent, requestCode);
答案 0 :(得分:1)
您可以尝试这样:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
List<Fragment> listOfFragments = getChildFragmentManager().getFragments();
if(listOfFragments.size()>=1){
for (Fragment fragment : listOfFragments) {
if(fragment instanceof yourFragmentName){
fragment.onActivityResult(requestCode, resultCode, data);
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}