Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get resource identifier from name

Tags:

android

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?

like image 681
Amin Sajedi Avatar asked Nov 04 '22 02:11

Amin Sajedi


1 Answers

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);
}
like image 116
Shade Avatar answered Nov 08 '22 08:11

Shade