Search code examples
androidjsonlistviewbaseadapter

Fetching data with respect to array with in array Json


I need to fetch two arrays from a json response Here is my response.

{
"data": [
    {
        "sub_cat": [
            {
                "id": "770",
                "cat_id": "14",
                "sub_category": "Pan America"
            },
            {
                "id": "771",
                "cat_id": "14",
                "sub_category": "John Players"
            }
        ],
        "id": "14",
        "cat_id": "x",
        "category": "Casual shirts"
    },
    {
        "sub_cat": [
            {
                "id": "770",
                "cat_id": "14",
                "sub_category": "Pan America"
            },
            {
                "id": "771",
                "cat_id": "14",
                "sub_category": "John Players"
            },
            {
                "id": "835",
                "cat_id": "15",
                "sub_category": "Roadster"
            },
            {
                "id": "836",
                "cat_id": "15",
                "sub_category": "wildcraft"
            }
        ],
        "id": "15",
        "cat_id": "x",
        "category": "Jackets"
    },
    {
        "sub_cat": [
            {
                "id": "770",
                "cat_id": "14",
                "sub_category": "Pan America"
            },
            {
                "id": "771",
                "cat_id": "14",
                "sub_category": "John Players"
            },
            {
                "id": "835",
                "cat_id": "15",
                "sub_category": "Roadster"
            },
            {
                "id": "836",
                "cat_id": "15",
                "sub_category": "wildcraft"
            },
            {
                "id": "833",
                "cat_id": "154",
                "sub_category": "Pepe jeans"
            },
            {
                "id": "834",
                "cat_id": "154",
                "sub_category": "John players"
            }
        ],
        "id": "154",
        "cat_id": "x",
        "category": "Jeans"
    }
],
"status": 100
}

While trying to fetch data, and put it in to a list adapter in which i want to display categories in one text box and subcategories in other with comma separation. Like this:

Category : Jeans

Sub Category :John players,Pepe jeans,Pan America,Roadster,wildcraft

I tried implementing this by creating model class for both category and sub category. Getting category correctly, but getting all subcategories.


Solution

  • Here is code for same:

     try{
            JSONObject jsonObject = new JSONObject(jsonString);
    
            ArrayList<String> categoryList = new ArrayList<>();
    
            HashMap<String,ArrayList<String>> allCategory = new HashMap<>();
            JSONArray dataArray  = jsonObject.getJSONArray("data");
            for(int i=0;i<dataArray.length();i++)
            {
                JSONObject internalObject = dataArray.getJSONObject(i);
    
                categoryList.add(internalObject.getString("category"));
    
                JSONArray jsonArray = internalObject.getJSONArray("sub_cat");
    
                ArrayList<String> subCategoryList = new ArrayList<>();
                for(int j=0;j<jsonArray.length();j++)
                {
                    subCategoryList.add(jsonArray.getJSONObject(j).getString("sub_category"));
                }
    
                allCategory.put(categoryList.get(i),subCategoryList);
            }
    
            Log.d("Check",hashMap+" ");
        }
        catch (Exception exe)
        {
            exe.printStackTrace();
        }
    

    You will get categoryList for all category and allCategory containing Hashmap. For mapping of category with its list of sub_categories.

    Edited

    Here is MainActivity.java class from where list is called:

    public class MainActivity extends Activity {
    
    ExpandableListAdapter listAdapter;
    ExpandableListView expListView;
    
    
    HashMap<String,ArrayList<String>> allCategory;
    private ArrayList<String> categoryList;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String[] mStrings = new String[20];
    
        allCategory= new HashMap<>();
    
    
        // get the listview
        expListView = (ExpandableListView) findViewById(R.id.lvExp);
    
        String jsonString = "{\n" +
                "\"data\": [\n" +
                "    {\n" +
                "        \"sub_cat\": [\n" +
                "            {\n" +
                "                \"id\": \"770\",\n" +
                "                \"cat_id\": \"14\",\n" +
                "                \"sub_category\": \"Pan America\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": \"771\",\n" +
                "                \"cat_id\": \"14\",\n" +
                "                \"sub_category\": \"John Players\"\n" +
                "            }\n" +
                "        ],\n" +
                "        \"id\": \"14\",\n" +
                "        \"cat_id\": \"x\",\n" +
                "        \"category\": \"Casual shirts\"\n" +
                "    },\n" +
                "    {\n" +
                "        \"sub_cat\": [\n" +
                "            {\n" +
                "                \"id\": \"770\",\n" +
                "                \"cat_id\": \"14\",\n" +
                "                \"sub_category\": \"Pan America\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": \"771\",\n" +
                "                \"cat_id\": \"14\",\n" +
                "                \"sub_category\": \"John Players\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": \"835\",\n" +
                "                \"cat_id\": \"15\",\n" +
                "                \"sub_category\": \"Roadster\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": \"836\",\n" +
                "                \"cat_id\": \"15\",\n" +
                "                \"sub_category\": \"wildcraft\"\n" +
                "            }\n" +
                "        ],\n" +
                "        \"id\": \"15\",\n" +
                "        \"cat_id\": \"x\",\n" +
                "        \"category\": \"Jackets\"\n" +
                "    },\n" +
                "    {\n" +
                "        \"sub_cat\": [\n" +
                "            {\n" +
                "                \"id\": \"770\",\n" +
                "                \"cat_id\": \"14\",\n" +
                "                \"sub_category\": \"Pan America\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": \"771\",\n" +
                "                \"cat_id\": \"14\",\n" +
                "                \"sub_category\": \"John Players\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": \"835\",\n" +
                "                \"cat_id\": \"15\",\n" +
                "                \"sub_category\": \"Roadster\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": \"836\",\n" +
                "                \"cat_id\": \"15\",\n" +
                "                \"sub_category\": \"wildcraft\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": \"833\",\n" +
                "                \"cat_id\": \"154\",\n" +
                "                \"sub_category\": \"Pepe jeans\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"id\": \"834\",\n" +
                "                \"cat_id\": \"154\",\n" +
                "                \"sub_category\": \"John players\"\n" +
                "            }\n" +
                "        ],\n" +
                "        \"id\": \"154\",\n" +
                "        \"cat_id\": \"x\",\n" +
                "        \"category\": \"Jeans\"\n" +
                "    }\n" +
                "],\n" +
                "\"status\": 100\n" +
                "}";
    
        // preparing list data
        prepareListData(jsonString);
    
        listAdapter = new ExpandableListAdapter(this, categoryList, allCategory);
    
    
        // setting list adapter
        expListView.setAdapter(listAdapter);
    
    
    }
    
    
    /*
     * Preparing the list data
     */
    private void prepareListData(String jsonString) {
        try{
            JSONObject jsonObject = new JSONObject(jsonString);
    
           categoryList = new ArrayList<>();
    
    
            JSONArray dataArray  = jsonObject.getJSONArray("data");
            for(int i=0;i<dataArray.length();i++)
            {
                JSONObject internalObject = dataArray.getJSONObject(i);
    
                categoryList.add(internalObject.getString("category"));
    
                JSONArray jsonArray = internalObject.getJSONArray("sub_cat");
    
                ArrayList<String> subCategoryList = new ArrayList<>();
                for(int j=0;j<jsonArray.length();j++)
                {
                    subCategoryList.add(jsonArray.getJSONObject(j).getString("sub_category"));
                }
    
                allCategory.put(categoryList.get(i),subCategoryList);
            }
    
            Log.d("Check",allCategory+" ");
        }
        catch (Exception exe)
        {
            exe.printStackTrace();
        }
    
    }
    }
    

    Here is Expandlist Adapter:

    public class ExpandableListAdapter extends BaseExpandableListAdapter {
    
    
    HashMap<String,ArrayList<String>> listDataEditText;
    
    int expandedGroup=0;
    
    private Context _context;
    private List<String> _listDataHeader; // header titles
    // child data in format of header title, child title
    private HashMap<String, ArrayList<String>> _listDataChild;
    
    
    
    
    
    
    public ExpandableListAdapter(Context context, List<String> listDataHeader,
                                 HashMap<String, ArrayList<String>> listChildData) {
        this._context = context;
        this._listDataHeader = listDataHeader;
        this._listDataChild = listChildData;
    
        listDataEditText  = new HashMap<>();
    
        for(int j=0;j<listDataHeader.size();j++) {
            ArrayList<String> preInsertion = new ArrayList<>();
            for (int i =0;i<this._listDataChild.get(_listDataHeader.get(j)).size();i++)
            {
                    preInsertion.add("");
            }
    
            listDataEditText.put(listDataHeader.get(j),preInsertion);
    
        }
    
    }
    
    
    @Override
    public Object getChild(int groupPosition, int childPosititon) {
        return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                .get(childPosititon);
    }
    
    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }
    
    
    
    
    @Override
    public View getChildView(final int groupPosition, final int childPosition,
                             boolean isLastChild, View convertView, ViewGroup parent) {
    
    
    
    
        final String childText = (String) getChild(groupPosition, childPosition);
    
        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.list_item, null);
        }
        TextView txtListChild = convertView.findViewById(R.id.lblListItem);
    
    
    
    
    
    
        txtListChild.setText(childText);
        return convertView;
    }
    
    
    
    
    
    @Override
    public int getChildrenCount(int groupPosition) {
        return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                .size();
    }
    
    @Override
    public Object getGroup(int groupPosition) {
        return this._listDataHeader.get(groupPosition);
    }
    
    @Override
    public int getGroupCount() {
        return this._listDataHeader.size();
    }
    
    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }
    
    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded,
                             View convertView, ViewGroup parent) {
        String headerTitle = (String) getGroup(groupPosition);
        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.list_group, null);
        }
    
        TextView lblListHeader = (TextView) convertView
                .findViewById(R.id.lblListHeader);
        lblListHeader.setTypeface(null, Typeface.BOLD);
        lblListHeader.setText(headerTitle);
    
    
    
    
        return convertView;
    }
    
    @Override
    public boolean hasStableIds() {
        return false;
    }
    
    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }
    
    
    
     }
    

    and here is list items:

    for GroupView "list_group":

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteY="81dp">
    
    <RelativeLayout
        android:id="@+id/relativeLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
    
        <TextView
            android:id="@+id/lblListHeader"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="48dp"
            android:text="TextView"
            android:textColor="#000000"
            android:textSize="33dp" />
    
    
    </RelativeLayout>
    </android.support.constraint.ConstraintLayout>
    

    for Child View "list_item":

     <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    <LinearLayout
        android:id="@+id/linearLayout4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.194"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.137">
    
        <TextView
            android:id="@+id/lblListItem"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:text="TextView"
            android:textColor="#000000"
            android:textSize="17dp" />
    
    </LinearLayout>
    
    
    </android.support.constraint.ConstraintLayout>
    

    Try it and let me know if need more.

    Edited latest

    Use this SimpleAdapter for showing all sub_categories list:

    public class SimpleAdapter extends BaseAdapter {
    
    
    ArrayList<String> stringArrayList;
    Context context;
    
    public SimpleAdapter(Context context,ArrayList<String> stringArrayList)
    {
        this.context = context;
        this.stringArrayList = stringArrayList;
    }
    
    @Override
    public int getCount() {
        return stringArrayList.size();
    }
    
    @Override
    public Object getItem(int i) {
        return null;
    }
    
    @Override
    public long getItemId(int i) {
        return 0;
    }
    
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if (view == null) {
            LayoutInflater infalInflater = (LayoutInflater) this.context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = infalInflater.inflate(R.layout.list_item, null);
        }
        TextView txtListChild = view.findViewById(R.id.lblListItem);
    
    
    
    
    
    
        txtListChild.setText(stringArrayList.get(i));
    
        return view;
    }
    }
    

    and make main layout as:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp"
    >
    
    
    
    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    </ListView>
    
    </LinearLayout>