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 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!