我有一个包含片段的活动:ConversationsFragment
以这种方式添加到活动中:
private void showFragment(BaseFragment fragment, String tag) {
FragmentTransaction transaction = fragmentManager
.beginTransaction()
.replace(R.id.content_frame, fragment, tag);
transaction.commit();
try {
fragmentManager.executePendingTransactions();
} catch (Exception e) {
Log.e(TAG, "Fail executing pending transactions", e);
}
}
在ConversationsFragment
中,我想添加一个"空案例"片段:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
searchEmptyCaseFragment = new SearchEmptyCaseFragment();
FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.empty_case_container, searchEmptyCaseFragment);
fragmentTransaction.commit();
getFragmentManager().executePendingTransactions(); //Added just for testing
getChildFragmentManager().executePendingTransactions(); //Added just for testing
}
但有时候,当我进入活动并快速离开时,我会得到这个例外:
E/AndroidRuntime( 8232): java.lang.RuntimeException: Unable to destroy activity {com.mycompany.messenger/com.mycompany.messenger.ui.activity.MainActivity}: java.lang.NullPointerException
E/AndroidRuntime( 8232): at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3273)
E/AndroidRuntime( 8232): at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3291)
E/AndroidRuntime( 8232): at android.app.ActivityThread.access$1200(ActivityThread.java:130)
E/AndroidRuntime( 8232): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1248)
E/AndroidRuntime( 8232): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 8232): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime( 8232): at android.app.ActivityThread.main(ActivityThread.java:4745)
E/AndroidRuntime( 8232): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 8232): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime( 8232): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
--
E/AndroidRuntime( 8232): Caused by: java.lang.NullPointerException
E/AndroidRuntime( 8232): at com.mycompany.ioc.IoCActivity.eK(SourceFile:57)
E/AndroidRuntime( 8232): at com.mycompany.ioc.IoCFragment.ahu(SourceFile:55)
E/AndroidRuntime( 8232): at com.mycompany.ioc.IoCFragment.onAttach(SourceFile:42)
E/AndroidRuntime( 8232): at com.mycompany.messenger.search.ui.SearchEmptyCaseFragment.onAttach(SourceFile:43)
E/AndroidRuntime( 8232): at android.support.v4.app.Fragment.onAttach(SourceFile:1152)
E/AndroidRuntime( 8232): at dh.a(SourceFile:968)
E/AndroidRuntime( 8232): at dh.a(SourceFile:1197)
E/AndroidRuntime( 8232): at cy.run(SourceFile:738)
E/AndroidRuntime( 8232): at dh.execPendingActions(SourceFile:1562)
E/AndroidRuntime( 8232): at dh.executePendingTransactions(SourceFile:535)
这基本上告诉我片段在活动被破坏时试图执行onAttach。
有没有办法确保在销毁活动之前已经执行了所有交易?
提前感谢您的时间。