使用RetroFit 2调用REST API展示RecyclerView时触发Resources$NotFoundException
解决你的Retrofit+RecyclerView崩溃问题
嗨,看你的Logcat错误信息,这个问题其实很常见——你在给TextView设置数字的时候用错了方法!
先看关键错误日志:
android.content.res.Resources$NotFoundException: String resource ID #0x1
at android.content.res.Resources.getText(Resources.java:339)
at android.widget.TextView.setText(TextView.java:5496)
这个错误的核心原因是TextView有两个重载的setText方法:
setText(int resId):传入资源ID,系统会去查找对应的字符串资源setText(CharSequence text):直接传入文本内容进行显示
你在Adapter绑定数据时,肯定是直接把rank、played这些Integer类型的值传进去了,比如:
// 错误写法!系统会把这个int当成资源ID去查找 textViewRank.setText(teamStandings.getRank());
而日志里的#0x1就是曼城的排名值,系统找不到ID为0x1的字符串资源,直接触发崩溃。
具体修复步骤
1. 修正TextView的文本设置方式
把所有数字类型的字段转成字符串再传入,推荐用String.valueOf(),清晰又安全:
// 正确写法:将数字转换为字符串后设置 textViewRank.setText(String.valueOf(teamStandings.getRank())); textViewPlayed.setText(String.valueOf(teamStandings.getPlayed())); textViewWin.setText(String.valueOf(teamStandings.getWin())); textViewDraw.setText(String.valueOf(teamStandings.getDraw())); textViewLoss.setText(String.valueOf(teamStandings.getLoss())); // 注意这里要同步修改字段名 // 其他数字字段(进球数、积分等)同理处理
2. 修复POJO类的字段映射错误
我还发现你的TeamStandings类里有个字段映射错误:
JSON里的败场字段是"loss",但你写的是@SerializedName("lose"),这会导致解析出来的败场值一直为null,后续使用该字段也会出问题,赶紧改成:
@SerializedName("loss") @Expose private Integer mLoss; // 对应的getter/setter也改成规范命名 public Integer getLoss() { return mLoss; } public void setLoss(Integer loss) { mLoss = loss; }
3. 额外的空值防护(可选但推荐)
API返回的字段可能存在null的情况,为了避免空指针异常,设置文本时可以加个判断:
Integer rank = teamStandings.getRank(); textViewRank.setText(rank != null ? String.valueOf(rank) : "-");
最后验证
先修改POJO的字段映射错误,再修正Adapter里的setText调用逻辑,重新运行App,应该就能正常加载并显示英超积分榜啦!
内容的提问来源于stack exchange,提问作者Obi
相关产品推荐
相关产品推荐

