I have a fragment with UI that is responsible for doing short async api-calls. When an async task completes fragment triggers a Toast message with a result-string.
My issue is that if a user presses Back button without waiting for the result the app crushes due to a onPostExecute method, which in turn triggers Toast + getString(R.string.whatever) in the fragment that is already detached, because the activity is behind the onDestroy state.
I can check whether the fragment is detached or use a ProgressDialog, which is modal but I think it would be nice to show the toasts without blocking or any other quirks. Any suggestions on how to achieve it? Broadcast receiver in the application class == overkill?
Thanks.
UPD logs:
01-24 12:01:29.626: E/AndroidRuntime(616):
java.lang.IllegalStateException: Fragment
HandsetSocialNetworksFragment{40612a78} not attached to Activity 01-24
12:01:29.626: E/AndroidRuntime(616): at
android.support.v4.app.Fragment.getResources(Fragment.java:571) 01-24
12:01:29.626: E/AndroidRuntime(616): at
android.support.v4.app.Fragment.getString(Fragment.java:593)
At the start of the async call, get the activity from the fragment, and get the application context from it. Use that one later to get the string you need.
Alternatively, you can fetch the string you need when you start the async call, instead of when you have to show the toast.