回收器中的Android片段数据加载
Posted
技术标签:
【中文标题】回收器中的Android片段数据加载【英文标题】:Android Fragment Data Loading in recycler 【发布时间】:2017-02-20 23:45:38 【问题描述】:我有一个 ProductListActivity,其中包含 viewpager 和 tablayout。我正在设置 Viewpager 的适配器,即 FragmentProductCategory。在 FragmentCategoryAdapter 构造函数中,传递上下文和 CategoryList 引用。 CategoryList 是一个简单的 pojo 类,它包含 categoryId 和 categoryName。在 FragmentCategoryAdapter 构造函数中,使用 for 循环我正在创建 ProductList (另一个包含产品相关信息的 pojo 类) ArrayList() 实例并将其再次存储在具有另一个构造函数的 CategoryList 类的另一个实例中。 现在从 FragmentCategoryAdapter 的 getItem() 我使用它的 newInstance() 方法创建 TabFragment 并根据其位置传递 ProductList 实例的引用。在 TabFragment 类中,它包含 recyclerview,我正在调用 asycntask 从服务器获取产品列表。我在 onPostExecute 中正确获取数据。然后使用 ProductListNotifyListener onTaskCompleted() 方法将其传递到片段并在此处设置 recyclerview 适配器。 但是在打开 ProductListActivity 时,第一个选项卡永远不会显示其加载数据。第二个问题是关于正在交换的滑动片段选项卡数据。 我没有得到我在这里做错了什么。请帮我。还请告诉我我是否以标准方式进行所有这些过程?还有其他方法吗? 我正在发布我的文件代码。
这是 ProductListActivity.java 类
public class ProductListActivity extends AppCompatActivity
private List<CategoryList> categoryLists;
private static Context context;
private TabLayout tabLayout;
private ViewPager viewPager;
public static FragmentProductCategory categoryAdapter;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_list);
context = ProductListActivity.this;
/* Get category list from SharedPreferences */
categoryLists = new AppSharedPreference(this).getCategoryLists();
/* Setting up toolbar */
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/* Displaying home page back button enabled */
ActionBar actionBar = getSupportActionBar();
if(actionBar!=null)
actionBar.setDisplayHomeAsUpEnabled(true);
//actionBar.setHomeAsUpIndicator(getResources().getDrawable(R.drawable.ic_back_arrow));
/* Drawable drawable = getResources().getDrawable(R.drawable.ic_back_arrow);
if(drawable!=null)
int color = Color.parseColor("#535353");
drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
*/
TextView textView = (TextView)toolbar.findViewById(R.id.titleToolbar);
textView.setTextColor(Color.parseColor("#535353"));
/* Setting tabs and titles as per no of categries */
/* Getting UI element's reference */
viewPager = (ViewPager) findViewById(R.id.viewPagerProductList);
tabLayout = (TabLayout) findViewById(R.id.tlProductList);
/*Creating fragment adapter class for tabs and setting it in viewpager */
categoryAdapter = new FragmentProductCategory(getSupportFragmentManager(),categoryLists,this);
viewPager.setAdapter(categoryAdapter);
/*Setting up tab layout with view pager and other effects*/
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.colorPrimary));
tabLayout.setTabTextColors(R.color.colorPrimary, R.color.colorPrimary);
tabLayout.setBackgroundColor(getResources().getColor(R.color.colorWhite));
tabLayout.setSelectedTabIndicatorHeight(6);
tabLayout.setSmoothScrollingEnabled(true);
/* Fetching intent data send from home activity and as per data get setting that particular tab */
String categoryId = getIntent().getStringExtra("category-id");
if(categoryId!=null)
int pos=0;
/* Looping through categoryList and matching categoryId received from intent to categoryList
* and on the basis of that fetching position of that particular tab
* */
for (int i=0;i<categoryLists.size();i++)
if(categoryLists.get(i).getCategoryId().equals(categoryId))
// Log.d("cat-id111", categoryLists.get(i).getCategoryId() + "\n pos=" + pos);
pos=i;
viewPager.setCurrentItem(pos);
/** Getting product list from server as per
* category-id from other pages has get or
* by default load data for first tab category id
**/
if(categoryId==null)
categoryId = categoryLists.get(0).getCategoryId();
这是 ProductList.java 简单的 pojo 类,用于存储产品列表信息。
public class ProductList
public String getCategoryId()
return categoryId;
public String getProductId()
return productId;
public String getProductName()
return productName;
public String getProductDetails()
return productDetails;
public String getProductPrice()
return productPrice;
public String getProductBarcode()
return productBarcode;
public String getStockQuantity()
return stockQuantity;
public String getOfferName()
return offerName;
public String getOfferPrice()
return offerPrice;
public String getThumb()
return thumb;
public String getBanner()
return banner;
public String getProductSize()
return productSize;
public void setProductSize(String productSize)
this.productSize = productSize;
public void setCategoryId(String categoryId)
this.categoryId = categoryId;
public void setProductId(String productId)
this.productId = productId;
public void setProductName(String productName)
this.productName = productName;
public void setProductDetails(String productDetails)
this.productDetails = productDetails;
public void setProductPrice(String productPrice)
this.productPrice = productPrice;
public void setProductBarcode(String productBarcode)
this.productBarcode = productBarcode;
public void setStockQuantity(String stockQuantity)
this.stockQuantity = stockQuantity;
public void setOfferName(String offerName)
this.offerName = offerName;
public void setOfferPrice(String offerPrice)
this.offerPrice = offerPrice;
public void setThumb(String thumb)
this.thumb = thumb;
public void setBanner(String banner)
this.banner = banner;
public ArrayList<String> getBannerList()
return bannerList;
public ArrayList<ProductContentList> getContentList()
return contentList;
public String categoryId;
public String productId;
public String productName;
public String productDetails;
public String productPrice;
public String productBarcode;
public String productSize;
public String stockQuantity;
public String offerName;
public String offerPrice;
public String thumb;
public String banner;
private ArrayList<String> bannerList;
private ArrayList<ProductContentList> contentList;
public ProductList(HashMap<String,String> hashMap)
this.categoryId=hashMap.get("categoryId");
this.productId=hashMap.get("productId");
this.productName=hashMap.get("productName");
this.productDetails=hashMap.get("productDetails");
this.productPrice=hashMap.get("productPrice");
this.productBarcode=hashMap.get("productBarcode");
this.productSize=hashMap.get("productSize");
this.stockQuantity=hashMap.get("stockQuantity");
this.offerName=hashMap.get("offerName");
this.offerPrice=hashMap.get("offerPrice");
this.thumb=hashMap.get("productImageLink");
prepareBannersAndContents(hashMap.get("bannerImageLinks"),hashMap.get("contentDetails"));
private void prepareBannersAndContents(String bannerLinks,String contentDetails)
try
JSONArray pBannerArr = new JSONArray(bannerLinks);
bannerList = new ArrayList<>();
for (int j=0;j<pBannerArr.length();j++)
bannerList.add(j,pBannerArr.getJSONObject(j).getString("imageLink"));
JSONArray pDetailsArr = new JSONArray(contentDetails);
contentList = new ArrayList<>();
for (int j=0;j<pDetailsArr.length();j++)
JSONObject object = pDetailsArr.getJSONObject(j);
contentList.add(new ProductContentList(object.getString("quantity"),object.getString("iconLink")));
catch (JSONException | NullPointerException jse)
jse.printStackTrace();
这是 FragmentProductCategory.java 视图页面适配器。
public class FragmentProductCategory extends FragmentStatePagerAdapter
private int PAGE_COUNT;
private List<CategoryList> catList;
public static List<CategoryList> dataList;
public FragmentProductCategory(FragmentManager fragmentManager1, List<CategoryList> catList, Context context1)
super(fragmentManager1);
this.catList=catList;
this.PAGE_COUNT = catList.size();
dataList = new ArrayList<>();
for(int i=0;i<catList.size();i++)
List<ProductList> pList = new ArrayList<>();
dataList.add(new CategoryList(catList.get(i).getCategoryId(), catList.get(i).getCategoryName(), pList));
Log.d("ProductListTest",""+i);
@Override
public Fragment getItem(int position)
Log.d("ProductListTest","getItem"+position);
return TabFragment.newInstance(position, dataList.get(position).getCategoryId(), dataList.get(position).getCategoryName());
@Override
public int getCount()
return PAGE_COUNT;
@Override
public CharSequence getPageTitle(int position)
return catList.get(position).getCategoryName();
public void applyFilters(int pos)
//tabFragment1.applyFilterSortSizeOperations(pos);
public static class TabFragment extends Fragment implements ProductListNotifyListener
private ProgressBar progressBar;
private LinearLayout llNoData;
private TextView tvNoDataMsg;
private Button btnTryAgain;
private Context context;
private RecyclerView recyclerView;
private ProductListAdapter productAdapter;
// on scroll
private static int fromIndex = 0,loadLimit = 20;
private int pagePosition;
private String catId,catName;
private static TabFragment fragment;
public static TabFragment newInstance(int position,String catId,String catName)
Bundle args = new Bundle();
args.putInt("position", position);
args.putString("id", catId);
args.putString("name", catName);
fragment = new TabFragment();
fragment.setArguments(args);
return fragment;
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
pagePosition = getArguments().getInt("position");
catId = getArguments().getString("id");
catName = getArguments().getString("name");
context = getContext();
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
return inflater.inflate(R.layout.fragment_product_category,container,false);
@Override
public void onViewCreated(View view, Bundle savedInstanceState)
super.onViewCreated(view, savedInstanceState);
progressBar = (ProgressBar)view.findViewById(R.id.progressBar);
recyclerView = (RecyclerView) view.findViewById(R.id.rvProductCategory);
llNoData = (LinearLayout)view.findViewById(R.id.llNoData);
tvNoDataMsg = (TextView)view.findViewById(R.id.tvNoDataMsg);
btnTryAgain = (Button) view.findViewById(R.id.btnTryAgain);
tvNoDataMsg.setTypeface(new SetFonts(context).setSourceSansProRegularFonts(), Typeface.ITALIC);
GridLayoutManager linearLayoutManager = new GridLayoutManager(getContext(),2);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.addItemDecoration(new ItemOffsetDecoration(getContext(), R.dimen.item_offset_inner));
//new SoapClient(context).getProductList(catId, fromIndex, loadLimit, productLists, listAdditionalArgs, recyclerView, llNoData, progressBar,fragment,productAdapter);
final ArrayList<String> listAdditionalArgs = new ArrayList<>();
listAdditionalArgs.add(ProductListActivity.appliedProductSize);
listAdditionalArgs.add(ProductListActivity.appliedSort);
listAdditionalArgs.add(ProductListActivity.appliedMaxPrice);
listAdditionalArgs.add(ProductListActivity.appliedMinPrice);
new SoapClient(context).getProductListTest(catId,pagePosition, fromIndex, loadLimit, listAdditionalArgs,fragment,recyclerView,llNoData,progressBar);
recyclerView.addOnScrollListener(new ProductListScrollListener(linearLayoutManager, "",context)
@Override
public void onLoadMore(String current_page_id, int fromIndex)
//loadMoreData(current_page_id, productLists, fromIndex);
);
btnTryAgain.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
llNoData.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
// new SoapClient(context).getProductList(catId, fromIndex, loadLimit, productLists, listAdditionalArgs, recyclerView,llNoData,progressBar);
);
@Override
public void onResume()
super.onResume();
ProductListActivity.resetCartViewText();
//FragmentProductCategory.productAdapter.notifyData();
@Override
public void onTaskStart(RecyclerView recyclerView1,LinearLayout llNoData1,ProgressBar progressBar1)
llNoData1.setVisibility(View.GONE);
progressBar1.setVisibility(View.VISIBLE);
recyclerView1.setVisibility(View.GONE);
@Override
public void onTaskCompleted(int position, String response)
Log.d("ProductListTest","onTaskCompleted"+position);
List<ProductList> pList = dataList.get(position).getProductLists();
try
pList.clear();
JSONArray jsonArray = new JSONArray(response);
for(int i=0;i<jsonArray.length();i++)
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
HashMap<String,String> hashMap1 = new HashMap<>();
hashMap1.put("productId",jsonObject1.getString("productId"));
hashMap1.put("productName", jsonObject1.getString("productName"));
hashMap1.put("productDetails", jsonObject1.getString("productDetails"));
hashMap1.put("productPrice", jsonObject1.getString("productPrice"));
hashMap1.put("productBarcode", jsonObject1.getString("productBarcode"));
hashMap1.put("productSize", jsonObject1.getString("productSize"));
hashMap1.put("stockQuantity", jsonObject1.getString("stockQuantity"));
hashMap1.put("offerName", jsonObject1.getString("offerName"));
hashMap1.put("offerPrice", jsonObject1.getString("offerPrice"));
hashMap1.put("productImageLink", jsonObject1.getString("productImageLink"));
hashMap1.put("bannerImageLinks", jsonObject1.getString("bannerImageLinks"));
hashMap1.put("contentDetails", jsonObject1.getString("contentDetails"));
pList.add(new ProductList(hashMap1));
productAdapter = new ProductListAdapter(pList,context);
recyclerView.setAdapter(productAdapter);
productAdapter.notifyData();
dataList.get(position).setProductLists(pList);
catch (JSONException jse)
jse.printStackTrace();
@Override
public void onException()
llNoData.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
recyclerView.setVisibility(View.GONE);
这是 CategoryList.java,一个简单的 pojo 类,用于存储类别列表信息和 ProductList 实例引用。
public class CategoryList
private String categoryId,categoryName;
private List<ProductList> productLists;
private ProductListAdapter productListAdapter;
public CategoryList(String categoryId,String categoryName)
this.categoryId=categoryId;
this.categoryName=categoryName;
public CategoryList(String categoryId,String categoryName,List<ProductList> productLists)
this.categoryId=categoryId;
this.categoryName=categoryName;
this.productLists=productLists;
public String getCategoryId()
return categoryId;
public String getCategoryName()
return categoryName;
public List<ProductList> getProductLists()
return productLists;
public void setProductLists(List<ProductList> productLists)
this.productLists = productLists;
这是在 TabFragment.java 类中实现的 ProductListNotifyListener.java 接口
public interface ProductListNotifyListener
public void onTaskStart(RecyclerView recyclerView,LinearLayout llNoData,ProgressBar progressBar);
public void onTaskCompleted(int position,String response);
public void onException();
这是 ProductListAdapter.java,用于在 recylerview 中显示数据
public class ProductListAdapter extends RecyclerView.Adapter<ProductListAdapter.MyViewHolder>
public static List<ProductList> productLists;
private Context context;
private SetFonts setFonts;
private AppSharedPreference sharedPreference;
public AlertDialog alertDialogProductDetails;
public int productDetailsPosition;
public ProductListAdapter()
public ProductListAdapter(List<ProductList> productLists,Context context)
this.productLists=productLists;
this.context=context;
sharedPreference = new AppSharedPreference(context);
/* Getting reference of SetFont class */
setFonts = new SetFonts(context);
public class MyViewHolder extends RecyclerView.ViewHolder
TextView tvProductName,tvProductPrice,tvPriceSymbol;
ImageView ivProductThumb,ivInformation,ivCart;
public MyViewHolder(View view)
super(view);
ivProductThumb = (ImageView) view.findViewById(R.id.ivProductThumb);
ivInformation = (ImageView)view.findViewById(R.id.ivInformation);
ivCart = (ImageView)view.findViewById(R.id.ivCart);
tvProductName = (TextView) view.findViewById(R.id.tvProductName);
tvProductPrice = (TextView) view.findViewById(R.id.tvProductPrice);
tvPriceSymbol = (TextView)view.findViewById(R.id.tvPriceSymbol);
/* Applying custom fonts */
tvProductName.setTypeface(setFonts.setSourceSansProSemiboldFonts());
tvProductPrice.setTypeface(setFonts.setSourceSansProRegularFonts());
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.adapter_product_list,parent,false);
return new MyViewHolder(view);
@Override
public void onBindViewHolder(MyViewHolder holder, int position)
try
if(sharedPreference.isProductAddedInCart(productLists.get(position).getProductId()))
holder.ivCart.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_cart_added));
else
holder.ivCart.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_cart));
/* JSONArray jsonArray = new JSONArray(productLists.get(position).getThumb());
JSONObject jsonObject = jsonArray.getJSONObject(0);*/
String imageLink = productLists.get(position).getThumb();
Glide.with(context).load(imageLink).thumbnail(0.5f).animate(R.anim.fade_in).diskCacheStrategy(DiskCacheStrategy.ALL).placeholder(R.drawable.img_placeholder_1x1).into(holder.ivProductThumb);
holder.tvProductName.setText(productLists.get(position).getProductName());
holder.tvProductPrice.setText(productLists.get(position).getProductPrice());
catch (ArrayIndexOutOfBoundsException | NullPointerException jse)
jse.printStackTrace();
@Override
public int getItemCount()
if(productLists.size()>0)
return productLists.size();
return 0;
public void notifyData()
notifyDataSetChanged();
【问题讨论】:
请提供您的所有设计 (.xml),以便我详细说明。\ 并提供 AppSharedPreference、SetFonts、ProductContentList 文件。 嗨帕特里克,我已经解决了我的问题。并发布了我的答案。但是感谢您抽出宝贵的时间阅读我的帖子。再次感谢您 【参考方案1】:您好,我已在前天整理了我的问题。在 ProductListActivity 类中,我已将 List productLists 声明为导致问题的静态。我删除了静态关键字,问题就解决了。
【讨论】:
以上是关于回收器中的Android片段数据加载的主要内容,如果未能解决你的问题,请参考以下文章