Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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() {
            @Override
            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);
                startActivity(intent);
            }
        });

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