Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build an Interactive Story App Intents and Multiple Activities Introducing Intents

Why we pass this to the first parameter of the Intent object and not this.MainActivity?

Hi, Why we pass "this" to the first parameter of the Intent object and not this.MainActivity?, the context is our MainActivity so why not add the name of the file? I understand that "this" refer to the current activity but i want to know if they both valid.

instead of :

  Intent intent = new Intent(this, StoryActivity.class);

we should use:

  Intent intent = new Intent(MainActivity.this, StoryActivity.class);

Lauren Moineau

1 Answer

Hi noob developer. Because in startStory() the intent is executed in the MainActivity itself, so this is enough.

However, if you move all the code from the startStory() method to the onClick() method in the anonymous OnClickListener inner class, you would need to call MainActivity.this, as you would now be in an inner class.

startButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String name = nameField.getText().toString();
                Intent intent = new Intent(MainActivity.this, StoryActivity.class);
                Resources resources = getResources();
                String key = resources.getString(R.string.key_name);
                intent.putExtra(key, name);

I hope that makes sense :)

Lauren Moineau Thanks for the answer! :D I understand that so i only would call MainActivity.this if its in the onClick method, if its on its own method i would call this?

You're welcome @noob developer :)

  • If you need context in the activity itself, use this.
  • If you need context in an inner class of the activity (anonymous, like when using setOnClickListener(), or not), use ActivityName.this