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 Android Lists and Adapters (2015) Lists with RecyclerViews Custom Adapters and ViewHolder in RecyclerViews

Val Rich
Val Rich
3,802 Points

Using ButterKnife in the HourViewHolder

Wanted to try using Butterknife in the HourViewHolder class in the HourAdapter class. Only error I'm getting is when I try to inject the views into the HourViewHolder constructor.

public class HourViewHolder extends RecyclerView.ViewHolder {
    @InjectView(R.id.timeLabel) TextView mTimeLabel;
    @InjectView(R.id.summaryLabel) TextView mSummarylabel;
    @InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
    @InjectView(R.id.iconImageView) ImageView mIconImageView;

    public HourViewHolder(View itemView) {
        super(itemView);
        ButterKnife.inject(this); //<===== Here is where the error occurs. 
                                               //"this" isn't doing what it should?
                                              //             Causing a nullpointer exception.   

    }

    public void bindHour(Hour hour){
        mTimeLabel.setText(hour.getHour());
        mSummarylabel.setText(hour.getSummary());
        mTemperatureLabel.setText(hour.getTemperature()+"");
        mIconImageView.setImageResource(hour.getIconId());
    }
}

1 Answer

Jon Kussmann
PLUS
Jon Kussmann
Courses Plus Student 7,254 Points

Hi,

Using ButterKnife in a fragment or for an adapter is a little different than for an activity.

For a fragment/adapter you also need to pass in the view as a second parameter. In your case it would be:

ButterKnife.inject(this, itemView);
Val Rich
Val Rich
3,802 Points

That made it work like a charm. i was dang close though, must have missed that requirement when looking through. Thank You!