android - 在后台,当从堆栈中弹出 fragment 时,android应用程序崩溃

  显示原文与译文双语对照的内容
66 3

应用程序崩溃,当我点击服务器RPC时,当RPC正在进行时,我将应用程序放在 background 中。同时,RPC从服务器获取响应时,会从堆栈中弹出一个 fragment 。当弹出 fragment 时,应用程序崩溃。我已经阅读了关于创建,如果 Activity 被破坏,它将是空的。但不确定该如何实现这种情况。

下面是我的代码:

private void showFragment(SherlockFragment fragment) {
 FragmentManager fm = getSupportFragmentManager();
 fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
 FragmentTransaction ft = fm.beginTransaction();
 ft.replace(R.id.content, fragment);
 ft.commit();
}

我在执行以下行时遇到崩溃:

fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

Stacktrace:

01-15 16:37:44.435: E/AndroidRuntime(28049): FATAL EXCEPTION: main
01-15 16:37:44.435: E/AndroidRuntime(28049): java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
01-15 16:37:44.435: E/AndroidRuntime(28049): at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1299)
01-15 16:37:44.435: E/AndroidRuntime(28049): at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1310)
01-15 16:37:44.435: E/AndroidRuntime(28049): at android.support.v4.app.FragmentManagerImpl.popBackStack(FragmentManager.java:452)
01-15 16:37:44.435: E/AndroidRuntime(28049): at com.druva.inSync.ValidationActivity$2.run(ValidationActivity.java:93)
时间:原作者:0个回答

149 3

我遇到了同样的问题,我用一个标志解决了。它看起来有点像"特技特技",但它能完成工作

public abstract class PopActivity extends Activity {
 private boolean mVisible; 
 @Override
 public void onResume() {
 super.onResume();
 mVisible = true;
 }
 @Override
 protected void onPause() {
 super.onPause();
 mVisible = false;
 }
 private void popFragment() {
 if (!mVisible) {
 return;
 }
 FragmentManager fm = getSupportFragmentManager();
 fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
 }
}

所以当你在继续应用程序时单独实现上述代码时,你将在一个 fragment 中发现你实际想要弹出。你可以使用以下snipped解决这里问题:

public abstract class PopFragment extends Fragment {
 private static final String KEY_IS_POPPED ="KEY_IS_POPPED";
 private boolean mPopped;
 @Override
 public void onSaveInstanceState(Bundle outState) {
 outState.putBoolean(KEY_IS_POPPED, mPopped);
 super.onSaveInstanceState(outState);
 }
 @Override
 public void onCreate(@Nullable Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 if (savedInstanceState!= null) {
 mPopped = savedInstanceState.getBoolean(KEY_IS_POPPED);
 }
 }
 @Override
 public void onResume() {
 super.onResume();
 if (mPopped) {
 popFragment();
 }
 }
 protected void popFragment() {
 mPopped = true;
//null check and interface check advised
 ((PopActivity) getActivity()).popFragment();
 }
}
原作者:
...