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.

Sambhav Anand
2,010 PointsHow can I convert a user entered string to an integer or drawable object?
I want the user to enter his/her favorite color and then change the background of the screen based on his/her input. So how can I achieve this. I know that I'll have to use a try-catch block in-case the user enters a wrong color.
2 Answers

Jon Kussmann
Courses Plus Student 7,254 PointsAssuming you have a reference to their favorite color as mFavoriteColor, and the background you want to change as mBackgroundLayout, you can write a series of if statements.
if (mFavoriteColor.equals("red")) {
mBackgroundLayout.setBackgroundColor(Color.RED);
} else if (mFavoriteColor.equals("blue")) {
mBackgroundLayout.setBackgroundColor(Color.BLUE);
} else if (mFavoriteColor.equals("green")) {
mBackgroundLayout.setBackgroundColor(Color.GREEN);
} else {
mBackgroundLayout.setBackgroundColor(Color.BLACK);
}

anthony crowell
Courses Plus Student 10,953 PointsI would try for a more dynamic approach and set your variable to something like userColor = ""; then in your try catch statement or what ever type of loop you use, set that variable as the input from the user. With my variable choice make sure your looking for a string input like 'red' or such, if you are looking for a hexadecimal you will have to change your variable type and use some type of conversion.
Sambhav Anand
2,010 PointsSambhav Anand
2,010 PointsBut isn't there a more refined way to achieve this. This way I'll have to hard code various colors for my code to work. Isn't there a dynamic solution.