Sunday, 18 August 2013

Using Toasts and Dialogs in AsyncTask

Using Toasts and Dialogs in AsyncTask

I'm a newbie with Android and would appreciate confirmation (tips)
regarding the following.
I've defined a separate thread by extending the AsyncTask class. Within
this class I perform some Toasts and Dialogs within the AsyncTask's
onPostExecute and onCancelled methods. The toasts require the
application's context such that all I need do is:
Toast.makeText(getApplicationContext(),"Some String",1);
The dialogs are created using AlertDialog.Builder which also requires a
context in its constructor. Am I right in thinking that this context
should be the Activity's context? i.e.
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
where getActivity could be a user defined class that returns the current
activity. If so what is the best way to handle this situation? Creating a
class like getActivity or passing the current activity's context to the
AsyncTask's constructor?
I guess I'm trying to understand the use of Context - I have noticed that
memory leaks can be an issue (don't really understand this yet) and how
using getApplicationContext() is the best approach where possible.
Thanks!

No comments:

Post a Comment