int imageId = (Integer) intent.getExtras().get(ProfilePageNormalUser.class.getName());
InputStream is = getResources().openRawResource(imageId); // 崩潰
// Resources$NotFoundException: Resource ID #0x4
imageId = 4 (0x4) 並非有效的 R.raw.xxx 資源 ID。可能原因:
putExtra 時放入的是 drawable ID 而非 raw ID,或放入了位置索引而非資源 IDget(ProfilePageNormalUser.class.getName()) 取值 Key 與發送端 putExtra 的 Key 不一致res/raw/ 目錄下無對應文件
// 1. 發送端檢查
Intent intent = new Intent(this, TargetActivity.class);
// 正確:傳遞 raw 資源 ID (整數)
intent.putExtra("image_res_id", R.raw.my_image); // 如 0x7f040001
// 錯誤:傳遞 drawable ID
// intent.putExtra("id", R.drawable.my_image);
// 錯誤:傳遞數組索引
// intent.putExtra("id", position);
startActivity(intent);
// 2. 接收端驗證
int imageId = getIntent().getIntExtra("image_res_id", -1);
if (imageId == -1) {
// 處理無效 ID
return;
}
Log.d("DEBUG", "Received imageId: 0x" + Integer.toHexString(imageId)); // 應為 0x7f04xxxx
// 3. 類型區分:raw vs drawable
// openRawResource 只接受 R.raw.xxx
// drawable 用 BitmapFactory.decodeResource(res, R.drawable.xxx)
| 資源類型 | ID 範圍 (十六進制) | 訪問方法 |
|---|---|---|
| drawable | 0x7f02xxxx | BitmapFactory.decodeResource(res, id) |
| raw | 0x7f04xxxx | res.openRawResource(id) / res.openRawResourceFd(id) |
| layout | 0x7f03xxxx | LayoutInflater.inflate(id, parent) |
| string | 0x7f05xxxx | res.getString(id) |
| id (View) | 0x7f08xxxx | findViewById(id) |
0x4 顯然不在任何正常資源 ID 範圍內 (均以 0x7f 開頭)。
public static final String EXTRA_IMAGE_RES_ID = "extra_image_res_id";res/raw/,傳 R.raw.xxx
// 發送
intent.putExtra(EXTRA_IMAGE_RES_ID, R.drawable.my_image);
// 接收
int resId = getIntent().getIntExtra(EXTRA_IMAGE_RES_ID, -1);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId);
raw 文件不會壓縮,APK 體積暴增。大圖放 drawable-nodpi 或網絡下載