小编典典

如何使用JSON数组制作ExpandableListView

json

我想制作一个ExpandableListView,它从服务器(JSON数组)的响应中为其组及其子级获取数据。这是我的json:

  [
    {
        "
        "begdate": "23/07/2013",
        "nama": "OPTIK INTERNASIONAL",
        "img_id": 2,
        "alamat": "Jl. Nasional No 23 Meulaboh",
        "enddate": "23/07/2015",
    },
    {

        "begdate": "01/05/2013",
        "nama": "EL JOHN SMOKING LOUNGE",
         "img_id": 3,
        "alamat": "Bandara Sultan Iskandar Muda, Banda Aceh",
        "enddate": "30/04/2014",
    },
    {
        "begdate": "09/11/2012",
        "nama": "ESPRESSO COFFE",
        "img_id": 2
        "alamat": "JL. SOEKARNO HATTA No. 16-17, Simpang Dodi",
        "enddate": "09/11/2014",
    },
    {

        "begdate": "16/03/2012",
        "nama": "LUZI PERFUME",
         "img_id": 3,
        "alamat": "JL. MATA IE KETAPANG II",
        "enddate": "16/03/2014",
    }
    ]

“ alamat”和“ nama”将成为组,“ begdate”和“
enddate”将成为其子项。我从这里开始按照以下教程操作:http//en.wikicode.org/index.php/Custom_ExpandableListView,但是当我实现它时,我有错误我的代码有什么问题吗?这是我的logcat:

    08-16 15:18:34.541: E/AndroidRuntime(416): FATAL EXCEPTION: main
08-16 15:18:34.541: E/AndroidRuntime(416): java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
08-16 15:18:34.541: E/AndroidRuntime(416):  at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
08-16 15:18:34.541: E/AndroidRuntime(416):  at java.util.ArrayList.get(ArrayList.java:311)
08-16 15:18:34.541: E/AndroidRuntime(416):  at com.example.belajaraccordion.TerbaruSimasCard.fetchResponse(TerbaruSimasCard.java:106)
08-16 15:18:34.541: E/AndroidRuntime(416):  at com.example.belajaraccordion.TerbaruSimasCard.access$1(TerbaruSimasCard.java:85)
08-16 15:18:34.541: E/AndroidRuntime(416):  at com.example.belajaraccordion.TerbaruSimasCard$TerbaruAsyncTask.onPostExecute(TerbaruSimasCard.java:77)
08-16 15:18:34.541: E/AndroidRuntime(416):  at com.example.belajaraccordion.TerbaruSimasCard$TerbaruAsyncTask.onPostExecute(TerbaruSimasCard.java:1)
08-16 15:18:34.541: E/AndroidRuntime(416):  at android.os.AsyncTask.finish(AsyncTask.java:417)
08-16 15:18:34.541: E/AndroidRuntime(416):  at android.os.AsyncTask.access$300(AsyncTask.java:127)
08-16 15:18:34.541: E/AndroidRuntime(416):  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
08-16 15:18:34.541: E/AndroidRuntime(416):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-16 15:18:34.541: E/AndroidRuntime(416):  at android.os.Looper.loop(Looper.java:123)
08-16 15:18:34.541: E/AndroidRuntime(416):  at android.app.ActivityThread.main(ActivityThread.java:3683)
08-16 15:18:34.541: E/AndroidRuntime(416):  at java.lang.reflect.Method.invokeNative(Native Method)
08-16 15:18:34.541: E/AndroidRuntime(416):  at java.lang.reflect.Method.invoke(Method.java:507)
08-16 15:18:34.541: E/AndroidRuntime(416):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-16 15:18:34.541: E/AndroidRuntime(416):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-16 15:18:34.541: E/AndroidRuntime(416):  at dalvik.system.NativeStart.main(Native Method)

这是我的代码:

TerbaruSimasCard.java

public class TerbaruSimasCard extends Activity {

    private ProgressDialog dialog;
    private ArrayList<TerbaruModel>ListTerbaru;
    private ArrayList<ArrayList<ArrayList<ChildTerbaru>>> ListChildTerbaru;
    ListView list;
    String phone1, begdate1, enddate1,img_id1;
     @Override
     protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.terbarusimascard);
            ListTerbaru= new ArrayList<TerbaruModel>();
            ListChildTerbaru= new ArrayList<ArrayList<ArrayList<ChildTerbaru>>>();
            new TerbaruAsyncTask().execute();
     }
    public class TerbaruAsyncTask extends AsyncTask<Void, Void, String> {
        String url = ("http://www.domain.com/123");

        public TerbaruAsyncTask() {
            this.url=url;
        }

        protected void onPreExecute (){ 
            super.onPreExecute();
            dialog = ProgressDialog.show(TerbaruSimasCard.this,"", "melakukan pengambilan data...");
        }
        @Override
        protected String doInBackground(Void... params) {
            String result = "";
            try {
                result= Connection.get(url);
            } catch (Exception e){
                result = "";
                Log.d("test", e.getMessage());
            }
            return result;
        }

    @Override
    protected void onPostExecute (String result){
        super.onPostExecute(result);
        fetchResponse(result.replace("\n","").trim());
        dialog.dismiss();

    }


    }

private void fetchResponse (String result){
    if (!result.equals("")){
        try {
            JSONArray jsonArray = new JSONArray(result);
            TerbaruModel LT=null;
            ChildTerbaru CT=null;
            for (int i= 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject= jsonArray.getJSONObject (i);

                LT= new TerbaruModel (
                        jsonObject.optString("img_id"),
                        jsonObject.optString("nama"),
                        jsonObject.optString("alamat")
                        );
                ListTerbaru.add(LT);

                for (int j= 0; j <jsonArray.length(); j++) {
                    CT= new ChildTerbaru (
                    jsonObject.optString("begdate"),
                    jsonObject.optString("enddate")
                    );
                    ListChildTerbaru.get(i).get(j).add(CT);

                }
                ExpandableListView list = (ExpandableListView) findViewById(R.id.ExpandableListView01);

                TerbaruAdapter adapter = new TerbaruAdapter(this, ListTerbaru,ListChildTerbaru);
                list.setAdapter(adapter);

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

这是我的TerbaruAdapter.java:

public class TerbaruAdapter extends BaseExpandableListAdapter{
    Context context;
    ArrayList<TerbaruModel>ListTerbaru;
    ArrayList<ArrayList<ArrayList<ChildTerbaru>>> ListChildTerbaru;
    int count;

    public TerbaruAdapter (Context context, ArrayList<TerbaruModel>ListTerbaru,ArrayList<ArrayList<ArrayList<ChildTerbaru>>> ListChildTerbaru){
        this.context=context;
        this.ListTerbaru=ListTerbaru;
        this.ListChildTerbaru=ListChildTerbaru;
//      this.count=ListTerbaru.size();
//      this.count=ListChildTerbaru.size();
    }
    @Override
    public boolean areAllItemsEnabled()
    {
        return true;
    }


    @Override
    public ArrayList<ChildTerbaru> getChild(int groupPosition, int childPosition) {
        return ListChildTerbaru.get(groupPosition).get(childPosition);
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild,View convertView, ViewGroup parent) {

        ChildTerbaru ListChildTerbaru = (ChildTerbaru) ((ArrayList<ChildTerbaru>)getChild(groupPosition, childPosition)).get(0);
        ViewHolder holder= null;

        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.expandablelistview_child, null);

            holder=new ViewHolder();
            holder.begdate1=(TextView)convertView.findViewById(R.id.beg_date);
            holder.enddate1=(TextView)convertView.findViewById(R.id.end_date);
        }
        else{
            holder=(ViewHolder)convertView.getTag();
        }

        holder.begdate1.setText(ListChildTerbaru.getBegDate());
        holder.enddate1.setText(ListChildTerbaru.getEndDate());

        return convertView;
    }
    @Override
    public int getChildrenCount(int groupPosition) {
        return ListChildTerbaru.get(groupPosition).size();
    }

    @Override
    public TerbaruModel getGroup(int groupPosition) {
        return ListTerbaru.get(groupPosition);
    }

    @Override
    public int getGroupCount() {
        return ListTerbaru.size();
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {

        TerbaruModel ListTerbaru = (TerbaruModel) getGroup(groupPosition);
        ViewHolder holder= null;
        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.expandablelistview_group, null);

            holder=new ViewHolder();
            holder.nama=(TextView)convertView.findViewById(R.id.name);
            holder.alamat=(TextView)convertView.findViewById(R.id.adress);
        }

         else{
            holder=(ViewHolder)convertView.getTag();
         }

        holder.nama.setText(ListTerbaru.getNama());
        holder.alamat.setText(ListTerbaru.getAlamat());

         return convertView;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public boolean isChildSelectable(int arg0, int arg1) {
        return true;
    }


    static class ViewHolder{
        TextView begdate1, enddate1,nama, alamat, imageid;
    }

}

我不知道我的错在哪里,是因为我在将JSON解析为波纹管时错了吗?

for (int i= 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject= jsonArray.getJSONObject (i);

            LT= new TerbaruModel (
                    jsonObject.optString("img_id"),
                    jsonObject.optString("nama"),
                    jsonObject.optString("alamat")
                    );
            ListTerbaru.add(LT);

            for (int j= 0; j <jsonArray.length(); j++) {
                CT= new ChildTerbaru (
                jsonObject.optString("begdate"),
                jsonObject.optString("enddate")
                );
                ListChildTerbaru.get(i).get(j).add(CT);

            }

还是还有其他什么问题?我希望有人能告诉我我的错在哪里…谢谢


阅读 184

收藏
2020-07-27

共1个答案

小编典典

修改您的适配器

 public class TerbaruAdapter extends BaseExpandableListAdapter{
    Context context;
    ArrayList<TerbaruModel>ListTerbaru;
    ArrayList<ArrayList<ChildTerbaru>> ListChildTerbaru;
    int count;

    public TerbaruAdapter (Context context, ArrayList<TerbaruModel>ListTerbaru,ArrayList<ArrayList<ChildTerbaru>> ListChildTerbaru){
        this.context=context;
        this.ListTerbaru=ListTerbaru;
        this.ListChildTerbaru=ListChildTerbaru;
//      this.count=ListTerbaru.size();
//      this.count=ListChildTerbaru.size();
    }
    @Override
    public boolean areAllItemsEnabled()
    {
        return true;
    }


    @Override
    public ChildTerbaru getChild(int groupPosition, int childPosition) {
        return ListChildTerbaru.get(groupPosition).get(childPosition);
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild,View convertView, ViewGroup parent) {

        ChildTerbaru childTerbaru = getChild(groupPosition, childPosition);
        ViewHolder holder= null;

        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.expandablelistview_child, null);

            holder=new ViewHolder();
            holder.begdate1=(TextView)convertView.findViewById(R.id.beg_date);
            holder.enddate1=(TextView)convertView.findViewById(R.id.end_date);
            convertView.setTag(holder);

        }
        else{
            holder=(ViewHolder)convertView.getTag();
        }

        holder.begdate1.setText(childTerbaru.getBegDate());
        holder.enddate1.setText(childTerbaru.getEndDate());

        return convertView;
    }
    @Override
    public int getChildrenCount(int groupPosition) {
        return ListChildTerbaru.get(groupPosition).size();
    }

    @Override
    public TerbaruModel getGroup(int groupPosition) {
        return ListTerbaru.get(groupPosition);
    }

    @Override
    public int getGroupCount() {
        return ListTerbaru.size();
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {

        TerbaruModel terbaruModel = (TerbaruModel) getGroup(groupPosition);
        ViewHolder holder= null;
        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.expandablelistview_group, null);

            holder=new ViewHolder();
            holder.nama=(TextView)convertView.findViewById(R.id.name);
            holder.alamat=(TextView)convertView.findViewById(R.id.address);
            convertView.setTag(holder);

        }

         else{
            holder=(ViewHolder)convertView.getTag();
         }

        holder.nama.setText(terbaruModel.getNama());
        holder.alamat.setText(terbaruModel.getAlamat());

         return convertView;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public boolean isChildSelectable(int arg0, int arg1) {
        return true;
    }


    static class ViewHolder{
        TextView begdate1, enddate1,nama, alamat, imageid;
    }

}

和你的活动

public class TerbaruSimasCard extends Activity {

    private ProgressDialog dialog;
    private ArrayList<TerbaruModel> ListTerbaru =  null;
    private ArrayList<ChildTerbaru> ListChildTerbaru =  null;
    private ArrayList<ArrayList<ChildTerbaru>> ListChildXXXXXXXXX = null;
    ListView list;
    String phone1, begdate1, enddate1, img_id1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.sample);
        ListTerbaru = new ArrayList<TerbaruModel>();
        ListChildTerbaru = new ArrayList<ChildTerbaru>();//ArrayList<ArrayList<ChildTerbaru>>>();
        ListChildXXXXXXXXX = new ArrayList<ArrayList<ChildTerbaru>>();
        new TerbaruAsyncTask().execute();
    }

    public class TerbaruAsyncTask extends AsyncTask<Void, Void, String> {
        String url = ("http:www.domain.com/123");

        public TerbaruAsyncTask() {
            this.url = url;
        }

        protected void onPreExecute() {
            super.onPreExecute();
            dialog = ProgressDialog.show(TerbaruSimasCard.this, "",
                    "melakukan pengambilan data...");
        }

        @Override
        protected String doInBackground(Void... params) {
            String result = "";
            try {
                result = Connection.get(url);
            } catch (Exception e) {
                result = "";
                Log.d("test", e.getMessage());
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            fetchResponse(result.replace("\n", "").trim());
            dialog.dismiss();
        }

    }

    private void fetchResponse(String result) {
        if (!result.equals("")) {
            try {
                JSONArray jsonArray = new JSONArray(result);
                TerbaruModel LT = null;
                ChildTerbaru CT = null;
                for (int i = 0; i < jsonArray.length(); i++) {
                    ListChildTerbaru = new ArrayList<ChildTerbaru>();
                    JSONObject jsonObject = jsonArray.getJSONObject(i);

                    LT = new TerbaruModel(jsonObject.optString("img_id"),
                            jsonObject.optString("nama"),
                            jsonObject.optString("alamat"));
                    ListTerbaru.add(LT);

                    //for (int j = 0; j < jsonArray.length(); j++) {
                        CT = new ChildTerbaru(jsonObject.optString("begdate"),
                                jsonObject.optString("enddate"));
                        ListChildTerbaru.add(CT);//get(i).get(i).add(CT);

                    //}
                        ListChildXXXXXXXXX.add(ListChildTerbaru);
                    ExpandableListView list = (ExpandableListView) findViewById(R.id.expandablelistView);

                    TerbaruAdapter adapter = new TerbaruAdapter(this,ListTerbaru, ListChildXXXXXXXXX);
                    list.setAdapter(adapter);

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}
2020-07-27