1

I have a Fragment in which I use an AsyncTask to send a tweet. I send the tweet in doInBackground, and when it's sent, onPostExecute is called and I'd like to show a Toast (or any notification) to the user.

The issue is that if the Fragment is paused (e.g. the user changed screens during the twitter request), no more context is available to call

Toast.makeText(Context context, CharSequence text, int duration)

I'm aware of other similar questions, like this one, but I couldn't find any answer...

... and keeping a local copy of the context seems very wrong.

Any suggestion?

Community
  • 1
  • 1
jul
  • 36,404
  • 64
  • 191
  • 318
  • I think.. you can use android:theme="@android:style/Theme.Dialog" to display a dialog when your app is not running too. – Ketan Ahir Aug 17 '13 at 08:16
  • @Kettu:it's irrelevant – Arash GM Aug 17 '13 at 08:23
  • 1
    Use an `IntentService` instead of `AsyncTask`, this way you can show `Toast` anytime. – M-Wajeeh Aug 17 '13 at 08:28
  • 1
    Or, just extend the `Application` class and (since it's already a singleton) set it up with a singleton accessor. Toasting on the application context will work just fine. If you feel like something more fancy, you can always set up your own singleton which keeps a reference to the application context for toasting messags. [See also here](http://stackoverflow.com/questions/3826905/singletons-vs-application-context-in-android/3827166#3827166). – MH. Aug 17 '13 at 08:34
  • @M-WaJeEh from [this answer](http://stackoverflow.com/a/16766109/326849), it's dangerous. – jul Aug 17 '13 at 08:41
  • @Jul Please consult rony l answer http://stackoverflow.com/a/5420929/1112882 – M-Wajeeh Aug 17 '13 at 08:54
  • Or this http://stackoverflow.com/a/18214792/1112882 – M-Wajeeh Aug 17 '13 at 08:55
  • @MH I'll use your solution, thanks. If you want to add it as an answer I'll accept it... – jul Aug 17 '13 at 09:03

1 Answers1

1

As per earlier comment:

You can extend the Application class and (since it's already a singleton) set it up with a singleton accessor. Toasting on the application context will work just fine. If you feel like something more fancy, you can always set up your own singleton which keeps a reference to the application context for toasting messages. See also here.

Community
  • 1
  • 1
MH.
  • 45,303
  • 10
  • 103
  • 116