上的片段IllegalStatexception

上的片段IllegalStatexception

本文介绍了在getResources()上的片段IllegalStatexception的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SubCategoryFragment中有这行:

s.group_name = SubCategoryFragment.this.getResources().getString(R.string.everything_else); // line 315 in stacktrace

我的理解是,通过添加SubCategoryFragment.this可以防止IllegalStatexception.

My understanding was that by adding SubCategoryFragment.this to this would prevent the IllegalStatexception.

这是一个ListFragment.当某人单击此片段中的列表项并转到另一个时,就会发生这种情况.然后单击后退按钮并返回到SubCategoryFragment. onActivityCreated()上面的这一行最终位于的位置.

This is a ListFragment. This occurs when someone clicks on a list item in this fragment, and goes to another; then hits the back button and returns to SubCategoryFragment. onActivityCreated() where this line above ultimately resides.

onDetach()内部,我与此无关.

java.lang.IllegalStateException:
  at android.support.v4.app.Fragment.getResources (Fragment.java:608)
  at ---.---.com.--.SubCategoryFragment.buildSubcategories (SubCategoryFragment.java:315)
  at ---.---.com.---.SubCategoryFragment$2.onResponse (SubCategoryFragment.java:287)
  at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run (ExecutorCallAdapterFactory.java:70)
  at android.os.Handler.handleCallback (Handler.java:751)
  at android.os.Handler.dispatchMessage (Handler.java:95)
  at android.os.Looper.loop (Looper.java:154)
  at android.app.ActivityThread.main (ActivityThread.java:6776)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1520)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1410)

推荐答案

Fragment.getResources()是一个便捷调用,可从您片段当前所连接的任何Activity中获取Resources对象.如果您的片段未附加任何活动,它将抛出IllegalStateException.

Fragment.getResources() is a convenience call that fetches the Resources object from whatever Activity your fragment is currently attached to. If your fragment isn't attached to any activity, it will throw IllegalStateException.

调用SubCategoryFragment.this.getResources()与仅调用getResources()并没有什么区别.

Calling SubCategoryFragment.this.getResources() vs just getResources() won't make any difference.

有两个可能的解决方案.第一种是将呼叫移到可以确保您的片段将附加到某些活动的位置.另一种方法是从片段以外的其他位置获取Resources对象(并因此获得片段的活动).如果您有权访问其他Context对象(也许通过打开View您可以调用View.getContext()),则可以改为调用Context.getResources().

There are two possible solutions to this problem. The first is to move the call to a place where you are guaranteed that your fragment will be attached to some activity. The other is to get a Resources object from somewhere other than the fragment (and therefore the fragment's activity). If you have access to some other Context object (perhaps by having a View you can call View.getContext() on), you can call Context.getResources() instead.

这篇关于在getResources()上的片段IllegalStatexception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 04:31