資料庫儲存字串 "R.drawable.logo",嘗試 Integer.parseInt(logo) 拋 NumberFormatException。
R.drawable.logo 是編譯時常數 int (如 0x7f080001),非字串可解析。資料庫存的是字面字串,無法直接轉換。
String resName = "logo"; // 僅存檔名,不含 R.drawable.
int resId = getResources().getIdentifier(resName, "drawable", getPackageName());
button.setBackgroundResource(resId);
"logo"),而非完整 "R.drawable.logo"2131230721),直接 setBackgroundResource(id)Cursor c = db.rawQuery("SELECT logo_name FROM items", null);
if (c.moveToFirst()) {
do {
String name = c.getString(0); // e.g. "logo"
int id = getResources().getIdentifier(name, "drawable", getPackageName());
if (id != 0) {
imageView.setImageResource(id);
}
} while (c.moveToNext());
}