Dyanamic tabs in android with dynamic content from json
<p>I m creating dynamic tabs in android in which the data for the tabs is populated from the json</p>

<p>Following is the json response</p>

<pre><code>    {
  "shop_details": [
    {
      "id": "36",
      "shop_name": "All in One Mart",
      "shop_no": "23223",
      "shop_address": "Tinkune",
      "phone": "9804966595",
      "email": "arjundangal4@gmail.com",
      "user_name": "arjun",
      "address": "",
      "tel": "",
      "fax": "",
      "facebook": "",
      "twitter": "",
      "googleplus": "",
      "image": "",
      "featured_image": ""
    }
  ],
  "category": [
    {
      "category_id": "35",
      "category_name": "Skirt",
      "product": [
        {
          "product_id": "49",
          "product_name": "Skirt",
          "category_id": "35",
          "subcategory_id": "37",
          "product_color": "blue",
          "description": "Skirt for girls",
          "price": "301",
          "discount": "0",
          "service_charge": "0",
          "user_id": "36",
          "image_name": "6baab8a5308b7e821f5b6387794979a4.jpeg",
          "created_at": "2016-07-04 03:54:54"
        }
      ]
    },
    {
      "category_id": "36",
      "category_name": "Men",
      "product": [
        {
          "product_id": "48",
          "product_name": "Glasses",
          "category_id": "36",
          "subcategory_id": "39",
          "product_color": "red",
          "description": "Glasses of Rayban",
          "price": "594",
          "discount": "23",
          "service_charge": "22",
          "user_id": "36",
          "image_name": "fce01420a9021fdb159226b4bdc5b591.jpg",
          "created_at": "2016-07-04 03:52:58"
        }
      ]
    },
    {
      "category_id": "37",
      "category_name": "Bags",
      "product": [
        {
          "product_id": "50",
          "product_name": "Laptop bag",
          "category_id": "37",
          "subcategory_id": "41",
          "product_color": "black",
          "description": "Bag to carry laptop",
          "price": "190",
          "discount": "2",
          "service_charge": "3",
          "user_id": "36",
          "image_name": "e836e090a54cd2b6b594fa0a3382bb38.jpg",
          "created_at": "2016-07-04 04:14:08"
        }
      ]
    }
  ]
}
</code></pre>

<p>Following is the code to fetch in which i add the tabs dynamically</p>

<pre><code> private void getShopDetails() {
    coordinatorLayout.setVisibility(View.GONE);
    new ProgressDialog(this);
    ProgressDialog.show();

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(shopDetailsJsonUrl, new Response.Listener&lt;JSONObject&gt;() {
        @Override
        public void onResponse(JSONObject response) {
            ProgressDialog.dismiss();
            coordinatorLayout.setVisibility(View.VISIBLE);

            try {
                JSONArray shopDetailsArray = response.getJSONArray("shop_details");
                JSONObject shopDetailsObj = shopDetailsArray.getJSONObject(0);
                shopName = shopDetailsObj.getString("shop_name");

                phone = shopDetailsObj.getString("tel");
                shopNum = shopDetailsObj.getString("shop_no");
                shopAddress = shopDetailsObj.getString("shop_address");
                shopImage = shopDetailsObj.getString("featured_image");
                Glide.with(getApplicationContext()).load("http://allmartapp.com/appapi/uploads/" + shopImage).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(backdrop);
                colLayout.setTitle(shopName);

                address.setText("Address - Shop no -" + shopNum + ", " + shopAddress);

                JSONArray tabsArray = response.getJSONArray("category");

                categoryId = new int[tabsArray.length()];

                for (int i = 0; i &lt; tabsArray.length(); i++) {

                    JSONObject tabsObj = tabsArray.getJSONObject(i);
                    tabLayout.addTab(tabLayout.newTab().setText(tabsObj.getString("category_name")));
                    categoryId[i] = tabsObj.getInt("category_id");

                }

                tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
                PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
                 pager.setAdapter(pagerAdapter);
                pager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

                tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                    @Override
                    public void onTabSelected(TabLayout.Tab tab) {
                        pager.setCurrentItem(tab.getPosition());
                        ShopDetailsTabsFragment.sgetid(categoryId[tab.getPosition()]);
                        Log.d("CATIID", categoryId[tab.getPosition()] + "");

                    }

                    @Override
                    public void onTabUnselected(TabLayout.Tab tab) {

                    }

                    @Override
                    public void onTabReselected(TabLayout.Tab tab) {

                    }
                });


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


        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            ProgressDialog.dismissWithError();
        }
    });

    int socketTimeout = 30000;//30 seconds - change to what you want
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    jsonObjectRequest.setRetryPolicy(policy);
    AppController.getInstance().addToRequestQueue(jsonObjectRequest);


}
</code></pre>

<p>In ontabselected() i assigned the category id according to the position of the tabs and call the sgetid() function which is in the fragment</p>

<p>My pageradapter returns only one Fragment with the recyclerview.
Following is the Fragment code</p>

<pre><code>public class ShopDetailsTabsFragment extends Fragment {
RecyclerView recyclerView;
boolean isViewShown = false;
CategoryListItemsAdapter shopListRvAdapters;

private String shopDetailsJsonUrl = "http://allmartapp.com/appapi/json/get_shop_details_by_shop_id/";

private String baseshopDetailsJsonUrl = "http://allmartapp.com/appapi/json/get_shop_details_by_shop_id/";

ArrayList&lt;CategoryItemsListModel&gt; arrayList = new ArrayList&lt;&gt;();
static int catid = 0;
int shopId;

public ShopDetailsTabsFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_shop_details_tabs, container, false);
    recyclerView = (RecyclerView) v.findViewById(R.id.rv);
    recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));

    SharedPreferences sharedPreferences = getActivity().getSharedPreferences("SHOPID", Context.MODE_PRIVATE);
    shopId = sharedPreferences.getInt("shopid", 0);

    return v;

}


@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (getView() != null) {
        isViewShown = true;
        getShopCat();

        // fetchdata() contains logic to show data when page is selected mostly asynctask to fill the data
    } else {
        isViewShown = false;
    }
}

public static void sgetid(int cat) {
    catid = cat;
}


private void getShopCat() {
    recyclerView.setAdapter(null);
    shopDetailsJsonUrl += shopId;
    arrayList.clear();
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(shopDetailsJsonUrl, new Response.Listener&lt;JSONObject&gt;() {
        @Override
        public void onResponse(JSONObject response) {
            Log.d("JSON", response.toString());

            try {
                JSONArray categoryArray = response.getJSONArray("category");

                for (int i = 0; i &lt; categoryArray.length(); i++) {
                    JSONObject catObj = categoryArray.getJSONObject(i);

                    int category_id = catObj.getInt("category_id");

                    if (category_id == catid) {

                        JSONArray productArray = catObj.getJSONArray("product");

                        for (int j = 0; j &lt; productArray.length(); j++) {
                            JSONObject productObj = productArray.getJSONObject(j);

                            String name = productObj.getString("product_name");
                            String image = productObj.getString("image_name");
                            int id = productObj.getInt("product_id");
                            int price = productObj.getInt("product_id");


                            CategoryItemsListModel shopListRvModels = new CategoryItemsListModel(id, image, name, price);
                            arrayList.add(shopListRvModels);
                            shopListRvAdapters = new CategoryListItemsAdapter(arrayList, getActivity());
                            recyclerView.setAdapter(shopListRvAdapters);
                            shopListRvAdapters.notifyDataSetChanged();
                        }
                    }

                }


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


        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });

    int socketTimeout = 30000;//30 seconds - change to what you want
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    jsonObjectRequest.setRetryPolicy(policy);
    AppController.getInstance().addToRequestQueue(jsonObjectRequest);
    shopDetailsJsonUrl = baseshopDetailsJsonUrl;

}


}
</code></pre>

<p>My problem is that, the tabs are showing strange behaviors. I know that the logic to fetch the category lists is correct. But I think there is problem in the state of the fragment. When i switch the tabs, the data loaded in the tabs are sometimes duplicated and even the data are loaded twice sometimes. Any suggestions are appreciated as im facing the problem for couple of days. I want to know the easy way to load the data in the tabs. </p>