Yesterday I read that using getApplicationContext() was potentially hazardous. Thus, code like this:
Toast.makeText(getApplicationContext(), "You mashed the button, dude.", Toast.LENGTH_SHORT).show();
...should be this instead:
Toast.makeText(MainActivity.this, "You mashed the button, dude.", Toast.LENGTH_SHORT).show();
(where "MainActivity" is the name of the class in which the code lives).
Yet I see many code snippets that include getApplicationContext(), such as:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
_initTask = new InitTask();
_initTask.execute( getApplicationContext() );
}
});
...from here. Is it really preferable to use <className
>.this over getApplicationContext()?
UPDATE
I've obviously still not understanding the niceties (or meanities) of this; with this code:
Toast.makeText(GetVendorsTask.this, s[0], Toast.LENGTH_SHORT).show();
I get this compilation err msg:
Error:(156, 18) error: no suitable method found for makeText(MainActivity.GetVendorsTask,String,int) method Toast.makeText(Context,CharSequence,int) is not applicable (argument mismatch; MainActivity.GetVendorsTask cannot be converted to Context) method Toast.makeText(Context,int,int) is not applicable (argument mismatch; MainActivity.GetVendorsTask cannot be converted to Context)
So I changed the complained-about line of code to:
Toast.makeText(MainActivity.this, s[0], Toast.LENGTH_SHORT).show();
...and it works (compiles). MainActivity
is the outermost class in the .java file (named MainActivity.java, that is); but GetVendorsTask
is the most proximate class (that line of code is within the GetVendorsTask
class). To be clear, the code is:
public class MainActivity extends ActionBarActivity {
. . .
class GetVendorsTask extends AsyncTask<Context, String, SearchResponse>
{
. . .
@Override
protected void onProgressUpdate(String... s)
{
super.onProgressUpdate(s);
//Toast.makeText(getApplicationContext(), s[0], Toast.LENGTH_SHORT).show(); <= "getApplicationContext()" might be null
//Toast.makeText(GetVendorsTask.this, s[0], Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, s[0], Toast.LENGTH_SHORT).show();
}
So replacing "GetVendorsTask" with "MainActivity" appeases the beast, but is it the best way to do it?
UPDATE 2
This sample code uses simply "this" in place of the other possibilities.