Hello.

With the Fragment API, the easy and straightforward way to access to
the i18n is to use the "Fragment.getString(int resId)" method.
Unfortunately, the implementation resorts to the underlying attached
Activity, which is only available between the
"Fragment.onAttach(Activity activity)" and the "Fragment.onDetach()"
methods life-cycle. As soon as a background thread attempts to invoke
the "Fragment.getString(int resId)" while the fragment is not attached
to its view, the caller thread gets an "IllegalStateException" with a
message of the form "Fragment MyfragmentClass{XXXXX} not attached to
Activity".

This involves that any worker thread which have been starting
executing a command when the fragment has been started, and which is
still being executing while the fragment has been detached (a typical
case is leaving the hosting activity), will need to check the
"Fragment.isDetached()" method, before attempting to access to the
i18n. One may claim that the background worker thread execution should
be interrupted as soon as the "Fragment.onDetach()" callback is
invoked, so as to get rid of the problem. But this leads to more code:
either to have a boolean somewhere to indicate whether the thread
should be still be running, or a test every time the "
"Fragment.getString()/getResources()/..." methods are invoked.

My question is: why not having exposed a "Fragment.getContext()"
method? A work-around, would be to define one, which returns
"getActivity().getApplicationContext()" as long as the fragment is
attached, and something like "getView().getContext()" in other cases.
But if the Android developers did not expose a "Fragment.getContext()"
method, coupled with a "private Context context" attribute, they must
have their reason. Is it to make the fragment more quickly garbage
collected, by reducing the amount of time when there is a double link
between between the fragment and its hosting activty?

To my opinion, accessing the Android context from a fragment or from
an activity should be done the same way (and this is actually the case
through the same for the "Activity/Fragment.getString()/
getResources()"), so as to ease porting activities to fragmented
activities. Did someone solve this problem of detached thread
accessing the i18n in an elegant and efficient way? What are your
thoughts about that issue?

Thank you for your time. Regards,
Édouard

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to