10

I have this method, and I want to use getResources() inside it:

 public void onBindViewHolder(ViewHolder viewHolder, int i) {

        viewHolder.itemTitle.setText(titles[i]);
        viewHolder.itemImage.setImageResource(images[i]);


       viewHolder.itemImage.setImageBitmap(
                decodeSampledBitmapFromResource(getResources(), R.id.item_image, 200, 200));
    }
1
  • 4
    you must have a Context reference variable in your adapter so use context.getResources() Feb 26, 2017 at 11:53

4 Answers 4

39
public void onBindViewHolder(ViewHolder viewHolder, int i) {
    Resources res = viewHolder.itemView.getContext().getResources();
    ...
}
1
  • This works great until you rotate the device and the Fragment is no longer attached to a context, causing a java.lang.IllegalStateException exception to be thrown. May 15, 2019 at 7:17
6

i can't use getResources inside onBindViewHolder()?

yes, you can. Use

   viewHolder.itemView.getResources();

getResources() is part View. No need to pass Context around

0

pass the Activity Context this in your Adapter class:

 Context context ;
 public YourAdapter(Context context ,... )  //constructor
 {
    this.context = context ;
    //other code
 }

then u can use:

context.getResources() ;
3
  • how do u call onAttach() in adapter..? Feb 26, 2017 at 12:16
  • no the comment was not meant for u...someone suggested to use onattach to get context !! Feb 26, 2017 at 15:33
  • You shouldn't pass context to the adapter, because it can lead to memory leaks. Mar 24, 2020 at 8:09
-1

get Context object by the Adapter constructor.

private Context context;

public YourAdapter(Context context){    //or you can make other method  to get/set Context obect
     this.context = context;
}

Then you can use this.context.getResources() to access getResources() method.

And initialize your adapter from Activity or Fragment, like -

YourAdapter yourAdapter = new YourAdapter(getApplicationContext());
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.