Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android

Ray Kennedy
PLUS
Ray Kennedy
Courses Plus Student 2,982 Points

Drawable is deprecated How should I structure my code

I am following the story application and when I write the following code

private void loadPage() { Page page = mStory.getPage(0);

        Drawable drawable = getResources().getDrawable(page.getImageId());
        mImageView.setImageDrawable(drawable);


        String pageText = page.getText();

        //This will add the name if placeholder included
        pageText = String.format(pageText, mName);
        mTextView.setText(pageText);

        mChoice1.setText(page.getChoice1().getText());
        mChoice2.setText(page.getChoice2().getText());
    }

this "get drawable" has a line drawn through it.

I've tried it like this: Drawable drawable = getResources().getDrawable(page.getImageId(), null); but that makes the system bark errors at me. Any help would be greatly appreciated.

1 Answer

Hello,

One way to make it so this is compatible both backwards and forwards is to use the ContextCompat class from the support library.

For example change

Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());

to

Drawable drawable = ContextCompat.getDrawable(this, mCurrentWeather.getIconId());

You also need to make sure you're importing the right class, but I believe just using the optimize your imports command should bring in the right one as long as the support library is included in your build.gradle file.