已添加非空判断仍触发java.lang.StringIndexOutOfBoundsException崩溃的原因分析及修复方案求助
Fixing the
StringIndexOutOfBoundsException in Your Code Hey, let's break down why this crash is happening and fix it right away.
The root cause isn't that your string is empty—you already covered that check. The problem pops up when settingsResponse.indexOf("FR") returns -1, which means the string doesn't contain the substring "FR" at all. Passing -1 to substring() triggers that fatal exception because substring can't start at a negative index.
How to Fix It
You need an extra check to confirm "FR" actually exists in the string before trying to substring it. Here's the adjusted code:
if(!settingsResponse.isEmpty()) { int frIndex = settingsResponse.indexOf("FR"); // Only proceed if "FR" is found in the string if (frIndex != -1) { String[] parts = settingsResponse.substring(frIndex).split("P_"); String front = "", in = "", rear = ""; for (int i = 0; i < parts.length; i++) { String part = parts[i].replace("\"", "").replace("P", "").replace(";", "").trim().replace(" ", ""); if (part.contains("FR")) { front = part; } else if (part.contains("IN")) { in = part; } else if (part.contains("R")) { rear = part; } Log.i("TAG", "onChanged111: " + part); } Log.i("TAG", "onChanged111: " + selectedPosition); if (front.equals("FR2160") && in.equals("") && rear.equals("")) { selectedPosition = 0; } else if (front.equals("FR1520") && in.equals("") && rear.equals("")) { selectedPosition = 1; } else if (front.equals("FR1440") && in.equals("") && rear.equals("")) { selectedPosition = 2; } else if (front.equals("FR1080") && in.equals("") && rear.equals("")) { selectedPosition = 3; } else if (front.equals("FR720") && in.equals("") && rear.equals("")) { selectedPosition = 4; } } else { // Optional: Handle the case where "FR" isn't present Log.w("TAG", "settingsResponse doesn't contain 'FR'"); // You could set default values or skip this logic entirely here } }
Key Takeaways
- Always validate the result of
indexOf()before using it insubstring()—a return value of-1means the target substring wasn't found. - This check ensures your code avoids invalid string operations, even when the input is non-empty but doesn't match your expected format.
- For long-term robustness, consider adding fallback logic for cases where the input doesn't follow the structure you're expecting (like missing "FR", "IN", or "R" segments).
内容的提问来源于stack exchange,提问作者MARSH
相关产品推荐
相关产品推荐

