Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build an Interactive Story App (Retired) Finishing the User Interface Formatting Strings

Amir Assadollahzadeh
Amir Assadollahzadeh
2,811 Points

getDrawble(int) is deprecated

So for this function now it is advised to pass and int and a theme, In this case how would you do that Drawable drawable = getResources().getDrawable(page.getImageId()); if I make the second parameter null then I get an error and one fix it shows is to add @TargetApi(Build.VERSION_CODES.LOLLIPOP) to the top of the function loadPage Can you explain please.

3 Answers

Hello,

You'll likely want to be using ContextCompat.getDrawable() from the support library. This is the current method for supporting older APIs as well as well. You do have to import ContextCompat. You will need to pass in the context(which will be the activity that you are in most likely) as well as the resource id. For example,

Drawable someDrawable = ContextCompat.getDrawable(this, R.id.drawable_id)

Please let us know if this helps or if you need more assistance.

In this case what would the drawable_id be?

In this case, the R.id.drawable_id would be the call to page.getImageId()

Vincent Rickey
Vincent Rickey
5,581 Points

Check out this stack overflow thread: http://stackoverflow.com/questions/29041027/android-getresources-getdrawable-deprecated-api-22

When I had this issue I simply just changed it to this: Drawable drawable = getDrawable(page.getImageId());

I believe when you're doing this, you're using the context's getDrawable(int) method. Looking in the documentation here, you'll notice that method was added in API 21, so if you try running the code on a device(or emulator) prior to API 21, your app will most likely crash.

this makes my app crashes !

Marko Jereb
Marko Jereb
1,771 Points

I just used ContextCompat.getDrawable(context, int id) and it works ok.

private Context mContext; mContext = getApplicationContext(); Drawable drawable = ContextCompat.getDrawable(mContext, page.getImageId());