-2

I am confused about where should we use

this,
className.this, 
context, 
getBaseContext 

like use this in 1:

Intent i = new Intent(this, secondClass.class); 

2:

  Toast.makeText(className.this,"",...).show;

why did we not use context here, and remaining others also?

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120

2 Answers2

1

There is no big difference between this and className.this.

'this' means "use this object", so className.this should be something like "use this object as an object of type className". I saw both used in the same way: If you want to pass the access the current object Im not sure about this but maybe className.this also includes a try to cast "this" to the class className (which may lead into an error if you try to className.this in an object which is className2 and not className)

So generally, the methods thisTest1 and 2 in the example below will lead to the same result:

class MyActivity extends Activity {

    void thisTest1() {
        startActivity(new Intent(this, secondClass.class));
    }


    void thisTest2() {
        startActivity(new Intent(MyActivity.this, secondClass.class));
    }

}

The different between getContaxt() and getBaseContext() is the following: The first gives you the context object of the used view or activity (eg. the activity context), while the BaseContext is the Context of the application. I usually only use the base context for view-unrelated operations like getting a SharedPreference or Database access while sticking to activity context for view dependent things like creating a new View object or getting an Inflater - and i ran pretty fine with that until now.

danijoo
  • 2,643
  • 4
  • 20
  • 42
0

In essence, it is something like this:

Activity extends ContextThemeWrapper extends ContextWrapper extends Context

In most cases, if it says Context then any of what you provided would work.

LuckyMe
  • 3,630
  • 2
  • 24
  • 35