java - 使用 JSON 响应中的数据填充 ExpandableListView

标签 java android expandablelistview expandablelistadapter

我的可扩展 ListView 有问题。我见过的有关父项目的所有教程都只有一项。就我而言,我正在父级和子级中使用多个字段(名称和评论)。我应该如何进行?

我的 json 数据

[
{
    nome: "Carlos",
    comentario: "Esse dia foi show",
    resp: [ ]
},
{
    nome: "Andre",
    comentario: "Acho que não precisava disso",
    resp: [
    {
        nome: "inutil",
        comentario: "Sempre assim"
    },
    {
        nome: "Roberto",
        comentario: "Se não estivessem fazendo nada errado, não iam querer apagar a mídia."
    },
    {
        nome: "xumbinho",
        comentario: "André ! Para vai!"
    }
    ]
},
{
    nome: "Celso",
    comentario: "É pra acabar mesmo",
    resp: [ ]
}
]

还有我的CommentariosActivity代码

private void makejsonobjreq() {
        PD.show();

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url+"284901",
                null, response -> {
                    ArrayList<Group> list = new ArrayList<Group>();
                    ArrayList<Child> ch_list;

                    Log.d("response", String.valueOf(response));
                    try {
                        Iterator<String> key = response.keys();
                        while (key.hasNext()) {
                            String k = key.next();
                            Log.d("KEY", String.valueOf(k));

                            Group gru = new Group();
                            gru.setNome(k);
                            ch_list = new ArrayList<Child>();

                            JSONArray ja = response.getJSONArray(k);
                            Log.d("QNT", String.valueOf(ja.length()));

                            for (int i = 0; i < ja.length(); i++) {

                                JSONObject jo = ja.getJSONObject(i);

                                Child ch = new Child();
                                Log.d("COMENTARIO NOME",jo.getString("nome"));
                                ch.setNome(jo.getString("nome"));
                                ch.setComentario(jo.getString("comentario"));

                                ch_list.add(ch);
                            } // for loop end
                            gru.setItems(ch_list);
                            list.add(gru);
                        } // while loop end

                        ExpAdapter = new ExpandListAdapter(ComentariosActivity.this, list);
                        ExpandList.setAdapter(ExpAdapter);

                        PD.dismiss();

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                PD.dismiss();
                Log.d("response", String.valueOf(error));
            }
        });
        MyApplication.getInstance().addToRequestQueue(jsonObjReq, "jreq");
    }

适配器

package br.inf.cgn.cgnapp;

import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;

import br.inf.cgn.cgnapp.model.Child;
import br.inf.cgn.cgnapp.model.Group;

public class ExpandListAdapter extends BaseExpandableListAdapter {

    private Context context;
    private ArrayList<Group> groups;

    ImageLoader imageLoader = MyApplication.getInstance().getImageLoader();

    public ExpandListAdapter(Context context, ArrayList<Group> groups) {
        this.context = context;
        this.groups = groups;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        ArrayList<Child> chList = groups.get(groupPosition).getItems();
        return chList.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) {

        Child child = (Child) getChild(groupPosition, childPosition);
        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) context
                    .getSystemService(context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.comentarios_resp, null);
        }

        if (imageLoader == null)
            imageLoader = MyApplication.getInstance().getImageLoader();

        TextView nome = (TextView) convertView.findViewById(R.id.nome_resp);
        nome.setText(child.getNome().toString());

        TextView comentario = (TextView) convertView.findViewById(R.id.comentario_resp);
        comentario.setText(child.getComentario().toString());

        return convertView;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        ArrayList<Child> chList = groups.get(groupPosition).getItems();
        return chList.size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return groups.get(groupPosition);
    }

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

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

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
                             View convertView, ViewGroup parent) {
        Group group = (Group) getGroup(groupPosition);
        if (convertView == null) {
            LayoutInflater inf = (LayoutInflater) context
                    .getSystemService(context.LAYOUT_INFLATER_SERVICE);
            convertView = inf.inflate(R.layout.comentarios_list, null);
        }
        TextView nome = (TextView) convertView.findViewById(R.id.nome);
        nome.setText(group.getNome());
        TextView comentario = (TextView) convertView.findViewById(R.id.comentario);
        comentario.setText(group.getComentario());

        return convertView;
    }

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

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

}

我尝试了多种方法来使该代码正常工作,但没有成功!

最佳答案

我添加了用于解析 JSON 响应并填充适配器数据的代码。这是一个完整的例子。但它需要一个带有名为“list”的 ExpandableListView 的 XML 文件。

我从另一篇 stackoverflow 帖子中借用了一个基本适配器。它只显示基本文本,而不是整个对话。但这可能足以让您解锁。但您需要将简单 View (例如 android.R.layout.simple_list_item_1)替换为您自己的 View 。

在实际应用中,最好在 ASyncTask 中解析 JSON 数据。

package com.example.elletlar.myapplication;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    List<Group> list = getList();
    ExpAdapter adapter = new ExpAdapter(this, list);
    ExpandableListView listView = findViewById(R.id.lst);
    listView.setAdapter(adapter);
}

public class Group {
    String name;
    private List<Child> childList;

    void setChildList(List<Child> list) {
        childList = list;
    }
    List<Child> getChildList() {
        return childList;
    }
}

public class Child {
    String name;
    String comment;
}

private ArrayList<Group> getList() {
    ArrayList<Group> list = new ArrayList<>();
    JSONArray groupArr;
    try {
        String TEST = "[" +
                "{" +
                "nome: \"Carlos\"," +
                "                comentario: \"Esse dia foi show\"," +
                "            resp: [ ]" +
                "    }," +
                "    {" +
                "        nome: \"Andre\"," +
                "                comentario: \"Acho que não precisava disso\"," +
                "            resp: [" +
                "        {" +
                "            nome: \"inutil\"," +
                "                    comentario: \"Sempre assim\"" +
                "        }," +
                "        {" +
                "            nome: \"Roberto\"," +
                "                    comentario: \"Se não estivessem fazendo nada errado, não iam querer apagar a mídia.\"\n" +
                "        }," +
                "        {" +
                "            nome: \"xumbinho\"," +
                "                    comentario: \"André ! Para vai!\"" +
                "        }" +
                "    ]" +
                "    }" +
                "]";

        groupArr = new JSONArray(TEST);
        ArrayList<Child> childList;

        for (int i = 0; i < groupArr.length(); ++i) {
            JSONObject groupObj= groupArr.getJSONObject(i);
            Group group = new Group();
            group.name = groupObj.getString("nome");

            childList = new ArrayList<>();
            JSONArray replyArr = groupObj.getJSONArray("resp");
            for (int j = 0; j < replyArr.length(); ++j) {
                JSONObject childObj = replyArr.getJSONObject(j);
                Child child = new Child();
                child.name = (childObj.getString("nome"));
                child.comment = (childObj.getString("comentario"));
                childList.add(child);
            } // for loop end

            group.setChildList(childList);
            list.add(group);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return list;
}

public class ExpAdapter extends BaseExpandableListAdapter {

    private final class ViewHolder {
        TextView textLabel;
    }

    private final List<Group> itemList;
    private final LayoutInflater inflater;

    private ExpAdapter(Context context, List<Group> itemList) {
        this.inflater = LayoutInflater.from(context);
        this.itemList = itemList;
    }

    @Override
    public Child getChild(int groupPosition, int childPosition) {

        return itemList.get(groupPosition).getChildList().get(childPosition);
    }

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

    @Override
    public int getChildrenCount(int groupPosition) {
        return itemList.get(groupPosition).getChildList().size();
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
                             final ViewGroup parent) {
        View resultView = convertView;
        ViewHolder holder;

        if (resultView == null) {
            resultView = inflater.inflate(android.R.layout.simple_list_item_1, null); //TODO change layout id
            holder = new ViewHolder();
            holder.textLabel = resultView.findViewById(android.R.id.text1); //TODO change view id
            resultView.setTag(holder);
        } else {
            holder = (ViewHolder) resultView.getTag();
        }

        final Child item = getChild(groupPosition, childPosition);

        holder.textLabel.setText(item.name);

        return resultView;
    }

    @Override
    public Group getGroup(int groupPosition) {
        return itemList.get(groupPosition);
    }

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

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

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View theConvertView, ViewGroup parent) {
        View resultView = theConvertView;
        ViewHolder holder;

        if (resultView == null) {
            resultView = inflater.inflate(android.R.layout.simple_list_item_1, null);
            holder = new ViewHolder();
            holder.textLabel = resultView.findViewById(android.R.id.text1);
            resultView.setTag(holder);
        } else {
            holder = (ViewHolder) resultView.getTag();
        }

        final Group item = getGroup(groupPosition);

        holder.textLabel.setText(item.name);

        return resultView;
    }

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

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }
}
}

以下是一些发出 HTTP 请求的示例: Using URLConnection

此外,您可能会考虑使用 Volley 框架: Volley

简单且非常流行的 HTTP 请求框架: OK HTTP

对于 Kotlin,我使用 Fuel: Fuel

请注意,Stackoverflow 上有关下载项目的大多数答案都使用来自 Apache 库的名为 DefaultHttpClient 的类。谷歌决定在几个 Android 版本前删除 Apache 库。仍然可以通过调整 Gradle 文件来使用它们,但这仅适用于旧版应用程序。新应用程序应该使用以下类:URLConnection。 Converting Apache to Current Android HTTP Classes

关于java - 使用 JSON 响应中的数据填充 ExpandableListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50157843/

相关文章:

android - 滚动时 ExpandableListView 的背景色

java - 如何在 Chrome 驱动程序中禁用 WebRTC?

java - 如何在 Swing 中创建立方体?

java - 向 caroufredsel 幻灯片添加文本

升级到版本 10.0 后,适用于 Eclipse 的 Android ADT 插件无法正常工作

android - 将可扩展 ListView 与 CollapsingToolbarLayout 一起使用时出现问题

java - "GMT"是 Java TimeZone 中的缩写吗?如果是的话可以使用它吗?

android - Dagger 2 : Unable to inject dependencies in WorkManager

当系统范围的字体放大时,Android TextView 不包装内容

java - 删除 ListView 项时出现空指针