android – 有时Fragment不附加到Activity(onCreateOptionsMenu)

前端之家收集整理的这篇文章主要介绍了android – 有时Fragment不附加到Activity(onCreateOptionsMenu)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
不知道为什么,但是我从Playstore中的应用程序收到一些错误报告,其中包含以下消息:
  1. java.lang.IllegalStateException: Fragment NewsOverViewFragment{4062e840} not attached to Activity
  2. at android.support.v4.app.Fragment.getResources(Fragment.java:601)
  3. at de.dala.simplenews.ui.NewsOverViewFragment.shouldUseMultipleColumns(NewsOverViewFragment.java:153)
  4. at de.dala.simplenews.ui.NewsOverViewFragment.updateMenu(NewsOverViewFragment.java:145)
  5. at de.dala.simplenews.ui.NewsOverViewFragment.onCreateOptionsMenu(NewsOverViewFragment.java:139)

我已经做了一个修复,并检查片段是否附加到活动,但这只是“避免”的问题.在我看来,它不应该发生在onCreateOptionsMenu或onOptionsItemSelected中获取一个未附加状态.

为什么会发生这种情况?片段如何调用onCreateOptionsMenu / onOptionsItemSelected而不附加到活动?

问候

码:

  1. @Override
  2. public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
  3. menu.clear();
  4. inflater.inflate(R.menu.news_overview_menu,menu);
  5. updateMenu();
  6. super.onCreateOptionsMenu(menu,inflater);
  7. }
  8.  
  9. private void updateMenu(){
  10. boolean useMultiple = shouldUseMultipleColumns();
  11. ...
  12. }
  13.  
  14. private boolean shouldUseMultipleColumns(){
  15. boolean useMultiple = false;
  16.  
  17. Configuration config = getActivity().getResources().getConfiguration();
  18. switch (config.orientation) {
  19. case android.content.res.Configuration.ORIENTATION_LANDSCAPE:
  20. useMultiple = PrefUtilities.getInstance().useMultipleColumnsLandscape();
  21. break;
  22. case android.content.res.Configuration.ORIENTATION_PORTRAIT:
  23. useMultiple = PrefUtilities.getInstance().useMultipleColumnsPortrait();
  24. break;
  25. }
  26.  
  27. return useMultiple;
  28. }

就像我说的,我现在检查片段是否附加,然后调用shouldUseMultipleColumns()来修复问题,但不能解释为什么这被称为首先…

编辑2:我的活动

  1. @Override
  2. protected void onCreate(Bundle savedInstanceState) {
  3. super.onCreate(savedInstanceState);
  4. setContentView(R.layout.activity_main);
  5. ...
  6. if (savedInstanceState == null) {
  7. if (getIntent().getDataString() != null) {
  8. String path = getIntent().getDataString();
  9. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  10. currentFragment = CategoryModifierFragment.getInstance(path);
  11. transaction.replace(R.id.container,currentFragment).commit();
  12. } else {
  13. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  14. currentFragment = NewsOverViewFragment.getInstance(NewsOverViewFragment.ALL);
  15. transaction.replace(R.id.container,currentFragment).commit();
  16. }
  17. }
  18. ...
  19. }

这基本上是附件程序.但是,可以调用总是替换currentFragment的其他片段,这样我的NewsOverViewFragment就没有附加的机会.但即使是这种情况 – 为什么要调用onCreateOptionsMenu?

解决方法

有时,使用onPostExecute方法时会出现此错误.
我这样处理了:
  1. protected void onPostExecute(Document result) {
  2. if (!isAdded())
  3. return;
  4. ........
  5. }

猜你在找的Android相关文章