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

Android Resources$NotFoundException异常原因及解决方法咨询

问题分析与解决:android.content.res.Resources$NotFoundException: String resource ID

异常原因

  1. setText方法重载误用:TextView的setText()有多个重载方法,当传入char类型值时,它会自动转换为对应的ASCII码整数,触发setText(int resId)重载——这个方法会把传入的整数当作字符串资源ID去系统资源中查找。但代码里传入的是OTP字符的ASCII值(比如字符'0'对应0x30),系统找不到该ID对应的资源,因此抛出Resources$NotFoundException。
  2. 字符串索引越界:代码中etInputOTP5.setText(otp.charAt(6))存在索引错误,6位OTP字符串的有效索引范围是0到5,访问索引6会导致StringIndexOutOfBoundsException,后续也会引发崩溃。

解决办法

1. 修正setText的参数类型

将char转换为String后再传入setText(),可以通过以下几种方式实现:

  • 使用String.valueOf(char)
  • 使用Character.toString(char)
  • 将字符与空字符串拼接(char + "")

2. 修正索引错误

把etInputOTP5的索引改为4,etInputOTP6保持索引5(原代码中两者索引顺序颠倒),确保在字符串的有效索引范围内访问。

修正后的代码

private void getOTPFromMessage(String message) { 
    Pattern otpPatter = Pattern.compile("(|^)\\d{6}");
    Matcher matcher = otpPatter.matcher(message);
    if (matcher.find()) {
        String otp = matcher.group().toString();

        System.out.println("otp = " + otp);
        System.out.println("otp.length() = " + otp.length());

        etInputOTP1.setText(String.valueOf(otp.charAt(0)));
        etInputOTP2.setText(String.valueOf(otp.charAt(1)));
        etInputOTP3.setText(String.valueOf(otp.charAt(2)));
        etInputOTP4.setText(String.valueOf(otp.charAt(3)));
        etInputOTP5.setText(String.valueOf(otp.charAt(4)));
        etInputOTP6.setText(String.valueOf(otp.charAt(5)));
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 11:40:33