4

I’m not sure why I’m getting this error only on certain Android versions (below 5.0).

I’m calling:

myImageView.setImageDrawable(getResources().getDrawable(R.drawable.image, null)); 

Because of this I’m getting a NoSuchMethodError.
What to do?

1
  • you can simple add your context in front of getDrawable() YOURCONTEXT.getResources().getDrawable(R.drawable.image, null) Commented Dec 29, 2017 at 12:27

4 Answers 4

8

Use this

myImageView.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.image)); 

Instead of this

myImageView.setImageDrawable(getResources().getDrawable(R.drawable.image, null)); 

EDIT

when you use setImageDrawable(getResources().getDrawable(R.drawable.image, null)); this it will shows below error

enter image description here

NOTE setImageDrawable(getResources().getDrawable(R.drawable.image, null)); this method is added in API level 21

You can read more about ContextCompat

Sign up to request clarification or add additional context in comments.

2 Comments

Ok I get it! Thanks
@Someday happy to help you
3

Use ContextCompat, it's helper class for accessing features in Context.

Using this class you can easily access the following resources,

  • ImageDrawable
  • String
  • Colour
  • ColorStateList
  • CodeCacheDir

And many more...

Try by following way,

myImageView.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.image)); 

Comments

1

@Prem answer is the right one. Just adding this to provide you with a tip.

In Android documentation there is an indication of which API level included each method. For example, the one you're using was introduced in Android 5.0 (API level 21).

API documentation example

Comments

1

You are calling getResources().getDrawable(R.drawable.image, null) method which is added in API level 21

check Android docs

If you are using second parameter (theme) as a null

So try to use

getResources().getDrawable(R.drawable.image); 

You can use following code for the same

myImageView.setImageDrawable(getResources().getDrawable(R.drawable.image)); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.