Akeshwar Jha
Akeshwar Jha

Reputation: 4576

Dynamically set image resource to a list-item

I'm creating a custom ListView with multiple elements - TextView and ImageView.

Here's a part of my getView method:

@override
public View getView(int position, View convertView, ViewGroup parent) {

        View itemView = convertView;
        if (itemView == null) {
            itemView = getLayoutInflater().inflate(R.layout.individual_items_in_options, parent, false);
        }

        // Find the option to start with.
        Options currentOption = optionsOfAQuestion.get(position);

        // option number
        TextView optionNumber = (TextView) itemView.findViewById(R.id.option_number);
        optionNumber.setText(currentOption.getOptionNumber());

        // option content
        TextView optionContent = (TextView) itemView.findViewById(R.id.option_content);
        optionContent.setText(currentOption.getOptionContent());

        ImageView imageView = (ImageView)findViewById(R.id.option_icon);
        imageView.setImageResource(R.drawable.icon_wrong);

I'm getting NPE while setting the image resource, though I've defined it in my layout. Why is setting image giving me NPE, while setting the TextViews work completely fine? What's the point I'm missing here?

Upvotes: 0

Views: 152

Answers (2)

prabhat yadav
prabhat yadav

Reputation: 93

replace this

ImageView imageView = (ImageView)findViewById(R.id.option_icon);

by this

  ImageView imageView = (ImageView)itemView.findViewById(R.id.option_icon);

this will help you

Upvotes: 2

Nidhin Prathap
Nidhin Prathap

Reputation: 722

Please Update your code like below

ImageView imageView = (ImageView) itemView .findViewById(R.id.option_icon);
imageView.setImageResource(R.drawable.icon_wrong);

Upvotes: 1

Related Questions