-1

I am trying to print a json response response in a recyclerview. my Recyclerview is like a expanded listView. And my json resone is like this:

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

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

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

and I trying to print this json resonse using this code:

    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;
        }
    }
}

But this code print nothing in my recycler UI.It show only a empty layout.I have also tried to print the response in my log and it prints whole response together.I want to print table1 contents in headers and table2 contents in as child(items) with their respective headers.how to do this?If any other information needed please ask..

Adi
  • 400
  • 8
  • 25
  • does it print something in stacktrace in logcat? Also have you tried debugging step by step? – Vladyslav Matviienko Nov 16 '16 at 06:26
  • Yes..t it prints the complete response only.. – Adi Nov 16 '16 at 06:41
  • Below is the right json format, please use this , it should work- {"Table1": [ {"filedate":"Oct 26, 2016"}, {"filedate":"Oct 18, 2016"} ], "Table2": [{"filedate":"Oct 18, 2016", "file1":"12.txt" }, {"filedate":"Oct 26, 2016", "file1":"acerinvoice.pdf"} ]} – Amit Nov 16 '16 at 06:53
  • THis is just a sample.. there is some suyntax error ..I have updated this..I have have already getting the complete response in my log. – Adi Nov 16 '16 at 07:02
  • you are looping inside another loop, "table2" in not inside "table1".... hope you understand... – noman404 Nov 16 '16 at 12:36

4 Answers4

1

You should probably check your response first of everything. As per your requirements you should use HashMap and ArrayList. Follow these following steps:

1.Take a ArrayLsit and store child data of 1st heading and so on with index starting from 0. 2.Store headers in HashMap as key.

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

Then use ExpandableListView to arrange parent and child items.

Rushi Ayyappa
  • 2,708
  • 2
  • 16
  • 32
0

please check your json response this is invalid json response first try to validate your json formate after try to decode and add in recycler view.

Raj Gohel
  • 524
  • 6
  • 11
  • I have already know that this is somwe way wrong..And I'm also trying some other thing..I want to know what is correct.. – Adi Nov 16 '16 at 06:39
0

Check Your Response into Logcat also the Exception. I've tested the Response you've supplied that contains some unnecessary "," that may cause the Exception.enter image description here

noman404
  • 928
  • 1
  • 8
  • 23
  • This is just a sample.. there is some suyntax error ..I have updated this..I have have already getting the complete response in my log. – Adi Nov 16 '16 at 07:03
  • Then Debug each line of your Code (the array size, the JSONObject ..etc). Try Log or Debug .. hope you'll find out the problem. – noman404 Nov 16 '16 at 09:21
  • the problem is in printing table2(i.e. child item). Can U please help? – Adi Nov 16 '16 at 09:36
0

I have solve my problem to just change above code like this..

     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);
    }
Adi
  • 400
  • 8
  • 25