【发布时间】:2013-03-11 12:58:54
【问题描述】:
我正在拼命尝试修复以下错误:
- 在我的 Android 版本 2.2、2.3 的模拟器中总是发生
- 在模拟器 android 版本 4 中永远不会发生。*
- 在真实设备中永远不会发生 (android 4.*)
是下面的IndexOutOfBoundsException异常:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{<myapppackage>}: java.lang.IndexOutOfBoundsException:
Invalid index 39, size is 0
在我的应用程序中,我正在从显示为文本的 json 文件中提取数据。我已经确定了错误的来源,它是在我调用此方法时:
public String getItemValue(int id, String s) {
List<JsonItems> list = new ArrayList<JsonItems>();
try {
// CONVERT RESPONSE STRING TO JSON ARRAY
JSONArray ja = new JSONArray(s);
// ITERATE THROUGH AND RETRIEVE
int n = ja.length();
for (int i = 0; i < n; i++) {
// GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY
JSONObject jo = ja.getJSONObject(i);
// RETRIEVE EACH JSON OBJECT'S FIELDS
JsonItems ji = new JsonItems();
ji.id = jo.getInt("id");
ji.text= jo.getString("text");
list.add(ji);
}
} catch (Exception e) {
e.printStackTrace();
}
return list.get(id).text;
}
我的 JsonItems 类非常基础:
public class JsonItems{
int id;
String text;
}
来自我的 json 文件的示例:
[
{"id":0,"text":"some text 0"},
{"id":1,"text":"some text 1"},
{"id":2,"text":"some text 2"}
]
这是我如何将 json 文件的内容处理为字符串
public static String fromJsonFileToString(String fileName, Context c) {
//JSONArray jArray = null;
String text = "";
try {
InputStream is = c.getAssets().open(fileName);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {
throw new RuntimeException(e);
}
return text;
}
我再重复一遍:IndexOutOfBoundsException 永远不会在装有 Android 4.* 的设备上发生,它只会在我在装有 Android 2.* 的模拟器上测试应用程序时发生
知道它是从哪里来的吗?
谢谢
【问题讨论】:
-
你把这个 for (int i = 0; i
-
您没有验证您的
id参数实际上小于计算列表的大小。坏的。这就是异常的直接原因。间接原因与构造 JSON 数组的方式有关。 -
除了您的代码在任何地方都无法优雅地处理问题(当然除了显式处理的列表长度之外)的意义上并不健壮这一明显事实之外,问题是,您确定jo 对象看起来总是一样的。换句话说,如何填充 JSON 数组。顺便说一句,如果你能指出异常所指的代码行就好了。
-
@Kintaro 你能发布一个导致问题的示例 json 吗?
-
感谢大家的 cmets,我已经用我的 json 文件样本编辑了我的问题。我的 Json 文件的内容是静态的,我怀疑它的内容有错误
标签: android json indexoutofboundsexception