我在开发的一个程序,从数据库的每个logo中读取resource name,然后设置 drawables。
但是当我想获取logo的整型字符串时,在Logcat中得到一个NumberFormatException。然后程序在启动时就强行关闭了。
代码如下:
String logo;
logo = c.getString(2);
button.setBackgroundResource(Integer.parseInt(logo));
logo
保存在数据库中:R.drawable.logo
如何处理这个问题呢?
button.setBackgroundResource这个是对应R生成的id
而你存储R.drawable.logo是个string,在parse的时候它并不认你是否是资源文件区转成id
而是当做string去转换,无疑你这边是错误的
你可以尝试存储int id = R.drawable.logo;
然后button.setBackgroundResource(id);
建议用此法
String logo = c.getString(2);//"logo"
int imgID = getResources().getIdentifier(logo, "drawable", "com.android.myTestPackageName"));
button.setBackgroundResource(imgID);