this
often to reference to current context. But, at some case, why we must use getBaseContext()
instead of this
. (It means when use this
will notice error).
Here is my example:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?>arg0, View arg1, int arg2, long arg3){
Toast.makeText(getBaseContext(),"SELECTED", Toast.LENGTH_SHORT).show(); //this line
}
At above code, when I change getBaseContext()
to this
will receive error.
Who can explain for me, please.
getBaseContext()
orgetApplicationContext()
unless you know exactly and specifically why you are using it. Newcomers to Java should spend time learning Java before getting into Android programming, so you will learn about things likeOuterClass.this
and not be confused when you encounter the need for them.getBaseContext()
andgetApplicationContext
this
because you are passing current Activty context but this method require onlyContext
object.