"this" in Toast.makeText()


Hi, I’m looking at the code to make the toast view for the checkAnswer method (page 43 in the 2013 edition). Can someone explain the this which is used as the context parameter? A similar one was used before when we made the original toast view, but there it was QuizActivity.this. I have used “this.makeSomething” before, but have never seen it coming after the class name.



This is one of those tricky Java things. The difference here is all in what “this” is.

Here’s some code that works something like the first chapter:

myButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Toast.makeTest(QuizActivity.this, "Howdy!", Toast.LENGTH_SHORT).show();

If you used “this” instead of “QuizActivity.this” in this code, it wouldn’t compile. That’s because it occurs inside onClick(), which is defined on your instance of View.OnClickListener - not QuizActivity. So “this” refers to the View.OnClickListener.

In the code on page 43, on the other hand (Listing 2.10), the method is defined on an Activity, so “this” refers to an Activity, and works fine.


I’m having a similar issue. I’m on page 43. I’m building my GeoQuiz app, but I’m doing it in the fragment form and not activity. I am receiving the error the method makeText(Context, int, int) in the type Toast is not applicable for the arguments (QuizActivity.PlaceholderFragment, int, int). I’m just lost on the way to convert this from the activity level to the fragment level. Any help would be greatly appreciated!


I had a similar problem. After messing around with the code for awhile I did something like this:

and it seemed to work for me.