缺少数据取决于选项卡的数量

时间:2018-07-25 11:13:13

标签: java android android-fragments

我想根据API保留的项目数创建多个标签。我已经成功创建了选项卡,并且滑动可以正常工作,但是问题是,例如,我有3个选项卡。当它们全部创建后,第一个和第二个选项卡为空,第三个选项卡具有数据,当我滑动回1时,我也看到了加载的数据,但从未在第二个选项卡上看到。选项卡为2时,都不显示数据。这是我的代码:

活动

public class MenuActivity extends AppCompatActivity {


    private ViewPager tabsPager;
    private Toolbar toolbar;
    private ImageView toolbarImageView;
    private TextView subTitleView, titleView, priceCounterView, itemsCounterView;
    private RatingBar ratingBar;
    private TabLayout tabLayout;
    private LinearLayout cartButton;
    private AVLoadingIndicatorView avi;
    private MenuPagerAdapter tabsAdapter;
    public List<MenuType> menuTypes = new ArrayList<>();
    public List<MenuItem> menuItems = new ArrayList<>();
    private Restaurant restaurant;
    private Context context;
    private CollapsingToolbarLayout collapsingToolbarLayout;
    private AppBarLayout appBarLayout;
    private int i = -1;
    public List<Fragment> fragments = new ArrayList<>();
    private int cartCount = 0;
    private int priceCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);
        context = this;

        tabsPager = (ViewPager) findViewById(R.id.tabs_pager);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        avi = (AVLoadingIndicatorView) findViewById(R.id.avi);
        titleView = (TextView) findViewById(R.id.titleView);
        subTitleView = (TextView) findViewById(R.id.subTitle);
        ratingBar = (RatingBar) findViewById(R.id.ratingBar);
        toolbarImageView = (ImageView) findViewById(R.id.restoIcon_toolbar);
        appBarLayout = (AppBarLayout) findViewById(R.id.app_bar);
        collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
        priceCounterView = (TextView) findViewById(R.id.items_price_counter);
        itemsCounterView = (TextView) findViewById(R.id.items_counter);
        cartButton = (LinearLayout) findViewById(R.id.view_order_button);

        if (cartCount == 0 && priceCount == 0){
            cartButton.setVisibility(View.GONE);
        }


        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        tabsPager.setCurrentItem(0);

        restaurant = (Restaurant) getIntent().getSerializableExtra("restaurant");

        collapsingToolbarLayout.setExpandedTitleColor(getResources().getColor(R.color.totalTransparent));

        getSupportActionBar().setTitle(restaurant.getName());
        titleView.setText(restaurant.getName());
        subTitleView.setText(restaurant.getSlogan());
        ratingBar.setRating(Float.parseFloat(restaurant.getRating()));

        Picasso.with(context)
                .load(restaurant.getImageURL())
                .placeholder(R.drawable.restaurant_placeholder)
                .into(toolbarImageView);

        loadMenuTypes();

    }

    //LOAD MENU TYPES

    public void loadMenuTypes(){

        RequestQueue queue = Volley.newRequestQueue(this);
        String url = getResources().getString(R.string.api) + "get-menu-types";
        final StringRequest postRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray array = jsonObject.getJSONArray("menu_types");

                            for (int i = 0; i < array.length(); i++){
                                JSONObject restoMainMenu = array.getJSONObject(i);

                                if (restoMainMenu.getBoolean("hasData")) {
                                    MenuType menuType = new MenuType();

                                    menuType.setMenuIcon(restoMainMenu.getString("icon"));
                                    menuType.setRestaurant(restaurant);
                                    menuType.setRmenu(restoMainMenu.getString("title"));
                                    menuType.setMenuId(restoMainMenu.getString("id"));

                                    menuTypes.add(menuType);
                                }
                            }


                        } catch (JSONException e) {
                            Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }

                        loadMenuItems();

                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        menuTypes.clear();
                        menuItems.clear();
                        loadMenuTypes();
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String>  params = new HashMap<String, String>();
                params.put("UID", restaurant.getId());

                return params;
            }
        };
        queue.add(postRequest);
    }

    //LOAD MENUS

    public void loadAllMenu(final MenuType mMenuType){

        RequestQueue queue = Volley.newRequestQueue(this);
        String url = getResources().getString(R.string.api) + "get-all-menu";
        StringRequest postRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray array = jsonObject.getJSONArray("detailed_menus");
                            List<MenuItem> menuItems1 = new ArrayList<>();
                            for (int i = 0; i< array.length(); i++){
                                JSONObject restoDetailMenu = array.getJSONObject(i);
                                MenuItem item = new MenuItem(
                                        restaurant.getId(),
                                        restoDetailMenu.getString("Name"),
                                        restoDetailMenu.getString("id"),
                                        restoDetailMenu.getString("Price"),
                                        restoDetailMenu.getString("Description"),
                                        restoDetailMenu.getString("AvailableIn"),
                                        restoDetailMenu.getString("Icon")

                                );


                                menuItems.add(item);
                                menuItems1.add(item);
                            }
                            mMenuType.setMenuItems(menuItems1);

                        }

                        catch (JSONException e) {
                            Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();

                        }
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        loadAllMenu(menuTypes.get(i));
                        Toast.makeText(context, error.getMessage(), Toast.LENGTH_SHORT).show();

                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String>  params = new HashMap<String, String>();
                params.put("MenuTypeId", mMenuType.getMenuId());
                params.put("restId", mMenuType.getRestaurant().getId());


                return params;
            }
        };
        queue.add(postRequest);
    }

    //TRIGER ALL MENU LOADER
    public void loadMenuItems(){

        for (int j = 0; j < menuTypes.size(); j++) {
            i = j;
            loadAllMenu(menuTypes.get(j));
        }

        avi.setVisibility(View.GONE);
        setUpTabs();
    }

    public void setUpTabs(){
        for (int j = 0; j < menuTypes.size(); j++) {
            tabLayout.addTab(tabLayout.newTab().setText(menuTypes.get(j).getRmenu()));
            MenuFragment fragment = new MenuFragment();
            Bundle bundle = new Bundle();
            bundle.putSerializable("data", menuTypes.get(j));
            fragment.setArguments(bundle);
            fragments.add(MenuFragment.newInstance(menuTypes.get(j)));
        }

        tabsAdapter = new MenuPagerAdapter(getSupportFragmentManager(), menuTypes);
        tabsAdapter.notifyDataSetChanged();
        tabsPager.setAdapter(tabsAdapter);
        tabLayout.setupWithViewPager(tabsPager);

        tabsPager.setAdapter(tabsAdapter);




    }

    public void addedToCart(int price){
        priceCount = priceCount + price;
        cartCount = cartCount + 1;

        if (cartCount > 0 && priceCount > 0){
            if (cartCount == 1){
                itemsCounterView.setText( String.valueOf(cartCount) + " item");
            } else {
                itemsCounterView.setText( String.valueOf(cartCount) + " items");
            }
            priceCounterView.setText(String.valueOf(priceCount) + " RWF");

            cartButton.setVisibility(View.VISIBLE);
        } else {
            cartButton.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }
}

PagerAdapter

public class MenuPagerAdapter extends FragmentStatePagerAdapter {

    private List<MenuType> menuTypes;

    public MenuPagerAdapter(FragmentManager fm, List<MenuType> menuTypes) {
        super(fm);
        this.menuTypes = menuTypes;
    }

    @Override
    public Fragment getItem(int position) {
        return MenuFragment.newInstance(menuTypes.get(position));
    }

    @Override
    public int getCount() {
        return menuTypes.size();
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {

        return menuTypes.get(position).getRmenu();
    }
}

片段

public class MenuFragment extends Fragment {

    @BindView(R.id.menuRecyclerView) RecyclerView menuRecyclerView;
    @BindView(R.id.avi) AVLoadingIndicatorView avi;
    private MenuType menuType;
    private Bundle args;
    private MenuAdapter adapter;
    private Context context;
    private int position;

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

    public static MenuFragment newInstance(MenuType mMenuType){
        MenuFragment fragment = new MenuFragment();
        Bundle args = new Bundle();
        args.putSerializable("data", mMenuType);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_menu, container, false);
        ButterKnife.bind(this, view);
        context = container.getContext();

        menuRecyclerView.setHasFixedSize(true);
        menuRecyclerView.setLayoutManager(new LinearLayoutManager(context));

        adapter = new MenuAdapter(menuType.getMenuItems(), context);
        menuRecyclerView.setAdapter(adapter);
        avi.setVisibility(View.GONE);

        setData();

        return view;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        args = getArguments();
        menuType = (MenuType) args.getSerializable("data");
    }

    public MenuType getMenuType() {
        return menuType;
    }

    public void setMenuType(MenuType menuType) {
        this.menuType = menuType;
    }


    public void setData(){
        adapter = new MenuAdapter(menuType.getMenuItems(), getActivity());
        menuRecyclerView.setAdapter(adapter);
        avi.setVisibility(View.GONE);
    }
}

可以看到,我先加载MenuTypes(List),然后对于每个MenuType,我也加载所有关联的项目(MenuItems)List。然后,我针对 MenuTypes 的数量创建Tab,然后针对列表中MenuItem的数量创建 MenuFragment 的实例,并为每个MenuFragment实例,我只是在RecyclerView中列出特定菜单类型的 MenuItems (工作正常)。我试图在MenuFragment中添加一个静态TextView,并且每次在所有选项卡上都显示了它,但是我想要的实际数据没有显示。我还尝试了一个临时解决方案,以手动从 OnPageChangeListener 中的“活动”中为每个创建的片段设置我想要的数据,但是直到我首先导航到任何其他标签时,它才直接在第一个标签上起作用,我选择退出该策略。任何帮助深表感谢。屏幕截图也包括在内以供参考。

When tabs are 2 (Screenshot)

When tabs are 2 (Screenshot)

3 tabs, at first, the tab 1 is empty (Screenshot)

3 tabs, last tab has data (Screenshot)

3 tabs, After navigating tabs, the tab 1 also got data (Screenshot)

3 tabs, tab 2 never gets data (Screenshot)

1 个答案:

答案 0 :(得分:0)

答案是使用Fragment的newInstance()函数,并将您最初想要的所有内容作为参数传递。