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 trialBoban Talevski
24,793 PointsGetting the context through the view that's passed in the onClick method instead of taking it through the constructor.
Isn't it a little better to get the context from the view that's passed in as parameter to the onClick method instead of taking it through the constructor and storing it as a member variable?
I think it makes for a cleaner code and maybe less prominent to crashes. I've read in some discussions on stackoverflow and some articles that passing the context around isn't always a great idea and could lead to memory leaks or something like that. I don't fully grasp those concepts yet, but I think I'd go for taking it from the view unless some other issues apply for that way of accessing it as well :).
This is what I'm talking about:
public void onClick(View view) {
String time = timeLabel.getText().toString();
String temperature = temperatureLabel.getText().toString();
String summary = summaryLabel.getText().toString();
String message = String.format("At %s it will be %s and %s",
time,
temperature,
summary);
Toast.makeText(view.getContext(), message, Toast.LENGTH_LONG).show();
}
The view that's passed in is the RelativeLayout from the hourly_list_item.xml and its context is the HourlyForecastActivity, so it works in the same way.
And we don't do any changes to the HourAdapter constructor, don't add a context member variable in HourAdapter to be set in the constructor, and don't change the call to the HourAdapter constructor from the HourlyForecastActivity class.
Can anyone share their opinion and pros and cons of getting the context in these two different ways?
1 Answer
Ben Deitch
Treehouse TeacherThat looks fine to me! I think the only real argument for passing it in the constructor would be if you needed access to the Context outside of the onClick method. Other than that, they should act exactly the same.
Boban Talevski
24,793 PointsBoban Talevski
24,793 PointsThanks for clearing it up, Ben!