p3ace p3ace - 3 months ago 34
Java Question

getDrawable(int) is deprecated and may produce a NullPointerException

I researched online and found related but not very similar information about comparing images and referring to images inside the

drawable
folder.

However, by following one of the answers I found in stackoverflow, I was able to compare two images and switch between them on button click.

I'm just concerned of the deprecated message I'm getting for
getDrawable(int)
.

What is really the correct way or syntax for getting drawable images and comparing them? It appears that
getDrawable()
isn't the correct one on that position.

Here's the code and screenshot of my working program.

private class myButtonListener implements View.OnClickListener{
@Override
public void onClick(View view) {
if(myImageView.getDrawable().getConstantState() ==
MainActivity.this.getResources().getDrawable(R.drawable.corgi).getConstantState() ){
myImageView.setImageResource(R.drawable.goldenretriever);
}else{
myImageView.setImageResource(R.drawable.corgi);
}
}
}


Screenshot of crossed out getDrawable() method.

enter image description here

enter image description here
enter image description here

Though my program is working, I want to make sure to avoid errors in the future for instances of deprecated methods.

I think this is important because like I mentioned I googled and got different information of which method or syntax to use.

Here's the modification solution for other users who may encounter the same problem.

private class myButtonListener implements View.OnClickListener{
@Override
public void onClick(View view) {
if(myImageView.getDrawable().getConstantState().equals(
ContextCompat.getDrawable(MainActivity.this,R.drawable.corgi).getConstantState() ) ){
myImageView.setImageResource(R.drawable.goldenretriever);
}else{
myImageView.setImageResource(R.drawable.corgi);
}
}
}

Answer

getDrawable() is deprecated in API level 22.

Use ContextCompat for that visit this : https://developer.android.com/reference/android/support/v4/content/ContextCompat.html#getDrawable(android.content.Context,%20int)

Use this way.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    return resources.getDrawable(id, context.getTheme());
} else {
    return resources.getDrawable(id);
}

As mention Here. Android getResources().getDrawable() deprecated API 22