Android片段数据在回收商

时间:2016-10-12 08:37:59

标签: android android-viewpager android-recyclerview fragment

我有一个ProductListActivity,其中包含viewpager和tablayout。我正在设置viewpager的适配器,它是FragmentProductCategory。在FragmentCategoryAdapter构造函数中,传递context和CategoryList引用。 CategoryList是简单的pojo类,包含categoryId&分类名称。在FragmentCategoryAdapter构造函数中,使用for循环我正在创建ProductList(另一个包含产品相关信息的pojo类)ArrayList()实例,并将它再次存储在另一个CategoryList类的实例中,并使用它的另一个构造函数。 现在从FragmentCategoryAdapter的getItem()创建TabFragment使用它的newInstance()方法并根据其位置传递ProductList实例的引用。在TabFragment类中,它包含recyclerview,我调用asycntask从服务器获取productlist。我在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 viewpager适配器。

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,一个存储类别列表信息和ProductList实例引用的简单pojo类。

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


}

1 个答案:

答案 0 :(得分:0)

您好我前天对我的问题进行了整理。在ProductListActivity类中,我已将List productLists声明为导致问题的静态。我删除了静态关键字,问题解决了。