You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发:为何无法将String转为int?附代码及报错日志求助

问题分析与解决方案

你遇到的崩溃根本不是String转整数的问题,而是Toast的使用错误导致的!

错误原因

看错误日志里的核心信息:

android.content.res.Resources$NotFoundException: String resource ID 0x9

这里的0x9就是你转换后的numero值(比如9)。Toast.makeText有两个重载方法:

  • 一个接受CharSequence类型(也就是字符串)
  • 另一个接受int类型,但这个int必须是字符串资源的ID(比如R.string.xxx这种系统或自定义的资源标识)

你直接把int类型的numero传进去,系统会误以为这是一个资源ID,去查找对应的字符串资源,而你的数值显然不是合法的资源ID,所以就抛出了找不到资源的异常。

修复方案

只需要把int类型的numero转换成字符串再传给Toast就行,有几种简单的方式:

  1. 使用String.valueOf(numero)
  2. 使用"" + numero
  3. 使用Integer.toString(numero)

修改后的完整代码示例:

Intent recibir = getIntent();
String nombre = recibir.getStringExtra("hora_inicio");
int numero = 0;
try {
    // 额外加个判空,避免nombre为null或空字符串时转换出错
    if (nombre != null && !nombre.trim().isEmpty()) {
        numero = Integer.parseInt(nombre);
    }
} catch(NumberFormatException nfe) {
    nfe.printStackTrace();
}
// 关键:把int转为String后再传入Toast
Toast.makeText(this, String.valueOf(numero), Toast.LENGTH_SHORT).show();

额外建议

虽然你的String转int代码加了try-catch,但提前判断nombre是否为null或者空字符串,能避免不必要的异常捕获,让代码更健壮。

内容的提问来源于stack exchange,提问作者Mimmetico

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:56:30