Android - 致命异常:添加 subList 时的 main

Android - FATAL EXCEPTION: main when adding subList

我目前正在处理我的第一个 Android 应用程序。 它解析 JSON 数据并将其放入 ListView(见下文)。

protected void onPostExecute(String result){

        try {
            JSONArray json = new JSONArray(result);

            for(int i = 0; i < json.length(); i++) {
                listItems.add(json.getJSONObject(i).getString(("title")));
                adapter.notifyDataSetChanged();
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

但是,当通过将函数更改为此来添加子列表时:

protected void onPostExecute(String result){

        try {
            JSONArray json = new JSONArray(result);

            List subList = listItems.subList(1,3);

            for(int i = 0; i < json.length(); i++) {
                listItems.add(json.getJSONObject(i).getString(("title")));
                subList.add("Test");
                adapter.notifyDataSetChanged();
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

它生成以下错误:

03-03 14:23:56.480  15414-15414/nl.mikehagendoorn.efteltijden E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: nl.mikehagendoorn.efteltijden, PID: 15414
java.lang.IndexOutOfBoundsException
        at java.util.AbstractList.subList(AbstractList.java:738)
        at nl.mikehagendoorn.efteltijden.Main$HttpAsyncTask.onPostExecute(Main.java:133)
        at nl.mikehagendoorn.efteltijden.Main$HttpAsyncTask.onPostExecute(Main.java:117)
        at android.os.AsyncTask.finish(AsyncTask.java:632)
        at android.os.AsyncTask.access0(AsyncTask.java:177)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

谁能告诉我哪里做错了?

问题在这里:

 List subList = listItems.subList(1,3);

如果 listItems 为空或少于四个元素,subList 将抛出 IndexOutBoundException。更准确地说,它在 (fromIndex < 0 || toIndex > size || fromIndex > toIndex).

时抛出 IndexOutBoundException

编辑:

I would like to put the title in the "Normal" list, and the date of the message in the sublist like this:

您可以使用带有两个 public 字段、标题和副标题的 class。例如

 public class Information {
    public String mTitle;
    public String mSubtitle;
 }

并且在您的 for-loop 中您可以:

  for(int i = 0; i < json.length(); i++) {
     Information tmp = new Information();
     tmp.mTitle = son.getJSONObject(i).getString(("title"));
     tmp.mSubtitle = "..";
     listItems.add(tmp);
  }

当然,您必须相应地更改您的列表以接受 object 类型 Information。在这种情况下,您需要的所有信息都包含在信息 object 中,减少了此类问题