我拼命地试图修复一个错误:
- 总是在我的 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.* 的模拟器上测试应用程序时才会发生
知道它来自哪里吗?
谢谢