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

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.