In my fragment, I am using resource strings at tons of places. Ideally, everything works fine.
But, I'm frequently getting crash reports for IllegalStateException saying Fragment is not attached to activity.
One possible solution I can imagine is using isAdded() method which returns if fragment is attached to activity or not, but using this at all places before accessing string resource doesn't seem a correct solution to me, as it can break the flow.
Also, can I use following implementation, not sure if it is correct?
Initialise mActivity on onAttach of fragment and then use it to get resource strings.
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Activity) {
mActivity = (Activity) context;
}
}
Instead of
getString(R.string.string_resource)
use
mActivity.getString(R.string.string_resource)
Can I be assured that using this will stop the IllegalStateExceptions?
Can I be assured that using this will stop the IllegalStateExceptions?
No, definitely not. Fragment.getString() internally delegates to requireContext().getResources(), and requireContext() will only return a value while the Fragment is attached to the Activity. So you'll really have the same issue, with more code.
Your issue is that you're calling getString() during an invalid part of the lifecycle. You mention that you're having this occur in a Retrofit response, so my assumption would be that you're submitting a network request within Fragment, and providing an anonymous response listener (which holds a reference to your Fragment). That request will continue even after the Fragment is detached, and then in your response listener you call getString().
Consider moving to the Android Architecture Components (specifically ViewModel and LiveData), and having your ViewModel perform the request, and post the result to a LiveData (which your Fragment can observe). That way you'll be guaranteed to only handle the result during a valid lifecycle state, and additionally the request will survive configuration changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With