我在android中创建了动态标签,其中标签的数据是从json
填充的以下是json回复
{
"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"
}
]
}
]
}
以下是获取的代码,我在其中动态添加标签
private void getShopDetails() {
coordinatorLayout.setVisibility(View.GONE);
new ProgressDialog(this);
ProgressDialog.show();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(shopDetailsJsonUrl, new Response.Listener<JSONObject>() {
@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 < 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);
}
在ontabselected()中,我根据选项卡的位置分配了类别id,并调用片段中的sgetid()函数
我的pageradapter只返回一个带有recyclerview的片段。 以下是片段代码
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<CategoryItemsListModel> arrayList = new ArrayList<>();
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<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("JSON", response.toString());
try {
JSONArray categoryArray = response.getJSONArray("category");
for (int i = 0; i < 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 < 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;
}
}
我的问题是,标签显示出奇怪的行为。我知道获取类别列表的逻辑是正确的。但我认为片段的状态存在问题。当我切换选项卡时,选项卡中加载的数据有时会重复,甚至有时会加载两次数据。任何建议都表示赞赏,因为我面临的问题几天。我想知道在标签中加载数据的简便方法。
答案 0 :(得分:0)
如果有帮助,请尝试以下代码:
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<CategoryItemsListModel> arrayList = new ArrayList<>();
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);
shopListRvAdapters = new CategoryListItemsAdapter(arrayList, getActivity());
recyclerView.setAdapter(shopListRvAdapters);
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<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("JSON", response.toString());
try {
JSONArray categoryArray = response.getJSONArray("category");
if(arrayList!=null){
if(arrayList.size()>0)
arrayList.clear();
}
for (int i = 0; i < 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 < 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");
arrayList.add(new CategoryItemsListModel(id, image, name, price));
}
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;
}