Fragment IllegalStatexception on getResources()

2019-08-26 23:02发布

问题:

I have this line inside SubCategoryFragment:

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

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

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.

I don't do anything inside onDetach() related to this.

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)

回答1:

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.

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

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.