Reputation: 135
I am developing an application that reads the resource name of each logo from database and then tries to set the drawables.
However, I get a NumberFormatException
in my Logcat when I try to obtain the integer identifier of the logo and my application suddenly force closes in the beginning of the application.
My code is as follows:
String logo;
logo = c.getString(2);
button.setBackgroundResource(Integer.parseInt(logo));
logo
is saved in the database as for example: R.drawable.logo
Do you have a suggestion what goes wrong here?
Upvotes: 5
Views: 379
Reputation: 20155
Try this
String logo=c.getString(2);
Get your drawable name, no need of R.drawable so removing them by splitting.
logo=logo.split("\\.")[2];
Third parameter is your package name
int drawableId = getResources().getIdentifier(logo, "drawable", "com.mypackage.myapp");
button.setBackgroundResource(drawableId);
Upvotes: 0
Reputation: 10001
If the value of logo
is "R.drawable.logo"
(a String
), then that can't be parsed to int
. R.drawable.logo is actually a reference to the static int logo
variable in the static class drawable
, which is a subclass of the generated resources class R
. R
is a generated resources class, which you can find in your project under the gen
folder.
You have to parse it yourself. If you know that it's a drawable that will be returned, you have to do something like:
String logoParts [] = logo.split ("\\.");
int logoId = getResources ().getIdentifier (logoParts [logoParts.length - 1], "drawable", "com.example.app");
Alternatively, you can separate it into a function:
public static int parseResourceString (Stinrg resString, String package) {
String resParts [] = resString.split ("\\.");
return getResources ().getIdentifier (resParts [resParts.length - 1], resParts [resParts.length - 2], package);
}
Upvotes: 2