JSON 响应在 Android 应用程序的回收站视图中使用 Volley

JSON response Using Volley in a recycler view in Android app

我正在尝试在 recyclerview 中打印 json 响应响应。我的 Recyclerview 就像一个扩展的 listView。而我的 json 共鸣是这样的:

{"Table1": 
[ 
{"filedate":"Oct 26, 2016"}, 
{"filedate":"Oct 18, 2016"} 
], 

"Table2": 
[{ 
"filedate":"Oct 18, 2016", 
"file1":"12.txt"
}, 

{ 
"filedate":"Oct 26, 2016", 
"file1":"acerinvoice.pdf" 
} 
]}

我尝试使用此代码打印此 json 响应:

    private void prepareListData() {

        // Volley's json array request object
        StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                new Response.Listener<String>() {

                //I think problrm is here
                    @Override
                    public void onResponse(String response) {

                        try {

                            **JSONObject object = new JSONObject(response);

                            JSONArray jsonarray = object.getJSONArray("Table1");
                            JSONArray jsonarray1 = object.getJSONArray("Table2");
                            for (int i = 0; i < jsonarray.length(); i++) {
                                try {

                                    JSONObject obj = jsonarray.getJSONObject(i);

                                   String str = obj.optString("filedate").trim();

                                    int lth = jsonarray1.length();


                                    data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.HEADER, str));
                               for (int j = 0; j < jsonarray1.length(); j++) {
                                        try {

                                            JSONObject obj1 = jsonarray1.getJSONObject(j);
                                            String str1 = obj1.optString("filedate").trim();

                                                data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str1));
                                                Toast.makeText(getApplicationContext(), str1, Toast.LENGTH_LONG).show();**

                                            //if condition


                                        } catch (JSONException e) {
//                                            Log.e(TAG, "JSON Parsing error: " + e.getMessage());
                                        }

                                    }

                                    // adding movie to movies array



                                } catch (JSONException e) {
                                    Log.e("gdshfsjkg", "JSON Parsing error: " + e.getMessage());
                                }

                            }
                            Log.d("test", String.valueOf(data));
                            Toast.makeText(getApplicationContext(), (CharSequence) data, Toast.LENGTH_LONG).show();

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

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data

                        recyclerview.setAdapter(new ExpandableListAdapter(data));
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(CLIENT, "4");
                return params;
            }
        };
        // Adding request to request queue
        MyApplication.getInstance().addToRequestQueue(stringRequest);
    }

ExpandableListAdapter

public class ExpandableListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    public static final int HEADER = 0;
    public static final int CHILD = 1;

    private List<Item> data;

    public ExpandableListAdapter(List<Item> data) {
        this.data = data;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int type) {
        View view = null;
        Context context = parent.getContext();
        float dp = context.getResources().getDisplayMetrics().density;
        int subItemPaddingLeft = (int) (18 * dp);
        int subItemPaddingTopAndBottom = (int) (5 * dp);
        switch (type) {
            case HEADER:
                LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.list_header, parent, false);
                ListHeaderViewHolder header = new ListHeaderViewHolder(view);
                return header;
            case CHILD:
                TextView itemTextView = new TextView(context);
                itemTextView.setPadding(subItemPaddingLeft, subItemPaddingTopAndBottom, 0, subItemPaddingTopAndBottom);
                itemTextView.setTextColor(0x88000000);
                itemTextView.setLayoutParams(
                        new ViewGroup.LayoutParams(
                                ViewGroup.LayoutParams.MATCH_PARENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT));
                return new RecyclerView.ViewHolder(itemTextView) {
                };
        }
        return null;
    }

    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        final Item item = data.get(position);
        switch (item.type) {
            case HEADER:
                final ListHeaderViewHolder itemController = (ListHeaderViewHolder) holder;
                itemController.refferalItem = item;
                itemController.header_title.setText(item.text);
                if (item.invisibleChildren == null) {
                    itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
                } else {
                    itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
                }
                itemController.btn_expand_toggle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (item.invisibleChildren == null) {
                            item.invisibleChildren = new ArrayList<Item>();
                            int count = 0;
                            int pos = data.indexOf(itemController.refferalItem);
                            while (data.size() > pos + 1 && data.get(pos + 1).type == CHILD) {
                                item.invisibleChildren.add(data.remove(pos + 1));
                                count++;
                            }
                            notifyItemRangeRemoved(pos + 1, count);
                            itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
                        } else {
                            int pos = data.indexOf(itemController.refferalItem);
                            int index = pos + 1;
                            for (Item i : item.invisibleChildren) {
                                data.add(index, i);
                                index++;
                            }
                            notifyItemRangeInserted(pos + 1, index - pos - 1);
                            itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
                            item.invisibleChildren = null;
                        }
                    }
                });
                break;
            case CHILD:
                TextView itemTextView = (TextView) holder.itemView;
                itemTextView.setText(data.get(position).text);
                break;
        }
    }

    @Override
    public int getItemViewType(int position) {
        return data.get(position).type;
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    private static class ListHeaderViewHolder extends RecyclerView.ViewHolder {
        public TextView header_title;
        public ImageView btn_expand_toggle;
        public Item refferalItem;

        public ListHeaderViewHolder(View itemView) {
            super(itemView);
            header_title = (TextView) itemView.findViewById(R.id.header_title);
            btn_expand_toggle = (ImageView) itemView.findViewById(R.id.btn_expand_toggle);
        }
    }

    public static class Item {
        public int type;
        public String text;
        public List<Item> invisibleChildren;

        public Item() {
        }

        public Item(int type, String text) {
            this.type = type;
            this.text = text;
        }
    }
}

但是这段代码在我的回收站中没有打印任何内容 UI.It 只显示一个空 layout.I 我也尝试在我的日志中打印响应并且它一起打印了整个响应。我想打印 headers 中的 table1 内容和 child(items) 中的 table2 内容及其各自的 headers。如何执行此操作?如果需要任何其他信息,请询问..

请检查您的 json 响应,这是无效的 json 响应首先尝试验证您的 json 甲酸,然后尝试解码并添加到回收站视图中。

您可能应该首先检查您的回复。根据您的要求,您应该使用 HashMap 和 ArrayList。按照以下步骤操作:

1.Take 一个 ArrayLsit 并存储 child 第一个标题的数据等等,索引从 0 开始。 2.Store headers 在 HashMap 中作为键。

ex: HashMap<String,ArrayList<Data>> hm; hm.put("your first heading string","related arraylist");

然后使用 ExpandableListView 排列 parent 和 child 项。

将您的回复检查到 Logcat 也是异常。我已经测试了您提供的响应,其中包含一些不必要的“,”,可能会导致异常。

我已经解决了我的问题,只需像这样更改上面的代码..

     private void prepareListData() {


        // Volley's json array request object
        StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {


                        JSONObject object = null;
                        try {
                            object = new JSONObject(response);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        JSONArray jsonarray = null;
                        JSONArray jsonarray1 = null;
                        try {
                            jsonarray = object.getJSONArray("Table1");
                            jsonarray1 = object.getJSONArray("Table1");

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

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

                                JSONObject obj = jsonarray.getJSONObject(i);
//                            
                                String str = obj.optString("filedate").trim();


                                Log.d("test", str);

                                data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.HEADER, str));

//                                    Toast.makeText(getApplicationContext(), lth, Toast.LENGTH_LONG).show();

                                    for (int j = 0; j < jsonarray1.length(); j++) {

                                        try {

                                            JSONObject obj1 = jsonarray1.getJSONObject(j);
                                            String str1 = obj1.optString("filedate").trim();
                                            String str3 = obj1.optString("category").trim();
                                            String str2 = obj1.optString("file1").trim();

                                            String str4 = obj1.optString("4").trim();
                                                Toast.makeText(getApplicationContext(), "server data respone", Toast.LENGTH_LONG).show();
                                                Toast.makeText(getApplicationContext(), "test"+str1, Toast.LENGTH_LONG).show();
                                            if (str == str1) {
//                                                data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str1));
                                                data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str3));
                                                data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str2));

                                            }
                                                Toast.makeText(getApplicationContext(), str1, Toast.LENGTH_LONG).show();

                                            //if condition


                                        } catch (JSONException e) {
//                                            Log.e(TAG, "JSON Parsing error: " + e.getMessage());
                                        }

                                    }

                                // adding movie to movies array



                            } catch (JSONException e) {
                                Log.e("gdshfsjkg", "JSON Parsing error: " + e.getMessage());
                            }

                        }
                        Log.d("test", String.valueOf(data));




                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
//                        adapterheader.notifyDataSetChanged();
                        recyclerview.setAdapter(new ExpandableListAdapter(data));
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
//                VolleyLog.d(TAG, "Error: " + error.getMessage());
//                hidePDialog();

            }
        }){
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(CLIENT, "4");
                return params;
            }
        };
        // Adding request to request queue
        MyApplication.getInstance().addToRequestQueue(stringRequest);
    }