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<noob />
17,062 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,062 Points<noob />
17,062 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