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.

<noob />
17,047 PointsWhy 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);
1 Answer

Lauren Moineau
9,483 PointsHi 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 :)
<noob />
17,047 Points<noob />
17,047 PointsLauren 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?
Lauren Moineau
9,483 PointsLauren Moineau
9,483 PointsYou're welcome @noob developer :)
this
.ActivityName.this