String size = parser.getValue(e, parser.KEY_FileSizeInByte); // "97035"
try {
int s = Integer.parseInt(size); // 正常轉換為 97035
Log.i("s", getString(s)); // 錯誤!將整數當作資源 ID 尋找字串資源
} catch (Exception e1) { ... }
Logcat 輸出:
W/ResourceType: No package identifier when getting value for resource number 0x00017b0b
I/error: String resource ID #0x17b0b
getString(int resId) 是 Context 方法,用於根據資源 ID 獲取字串資源 (如 R.string.app_name)。
代碼誤將解析後的整數 97035 (0x17B0B) 當作資源 ID 傳入,系統嘗試尋找 @string/0x17B0B,不存在 → 警告並返回異常字串。
| 需求 | 正確代碼 | 說明 |
|---|---|---|
| 字串轉整數 | int s = Integer.parseInt(size); | 純數值轉換 |
| 整數轉字串顯示 | String str = String.valueOf(s); 或 Integer.toString(s) | 數值轉字串 |
| 獲取 strings.xml 定義的字串 | getString(R.string.my_string) | 資源 ID 必須是 R 類生成的常數 |
| 格式化字串資源 | getString(R.string.format_size, s) | <string name="format_size">Size: %d MB</string> |
String sizeStr = parser.getValue(e, parser.KEY_FileSizeInByte);
Log.i("menuItems", sizeStr);
try {
long sizeBytes = Long.parseLong(sizeStr); // 用 long 防止大文件溢出
long sizeMB = sizeBytes / (1024 * 1024);
// 方式一:直接拼接
String display = "Size: " + sizeMB + " MB";
// 方式二:使用字串資源 (推薦,支援多語言)
String display = getString(R.string.file_size_format, sizeMB);
// strings.xml: Size: %d MB
Log.i("size", display);
// 設置到 TextView 等...
} catch (NumberFormatException e) {
Log.e(TAG, "無效文件大小: " + sizeStr, e);
}
String.valueOf(),後者用 getString(R.string.xxx)%d、%s、%.2f 等,便於國際化