为什么我的TabLayout给我一个NullPointerException,如何解决它?

时间:2018-07-27 13:20:11

标签: java android android-fragments android-activity

我已阅读"What is a NullPointerException and how do I fix it?",但无法回答我的问题。

好的,所以我在活动中有一个片段作为内部类。从该片段中,我试图调用活动类中的方法以从TabLayout中删除所有标签,但是由于某种原因,当我尝试分配{{1}时,我得到了 NullPointerException }对其资源进行编码。

以下是删除所有标签的方法:

TabLayout

这是调用它的代码:

public void removeAllTabs() {
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
    mTabLayout = findViewById(R.id.tabs);
    mViewPager = findViewById(R.id.container);

    int cnp = mSectionsPagerAdapter.getCount();
    while (cnp > 0) {
        mSectionsPagerAdapter.destroyItem(mViewPager, cnp - 1, mSectionsPagerAdapter.getItem(cnp - 1));
        mTabLayout.removeTabAt(cnp - 1);
        cnp--;
    }
}

这是堆栈跟踪:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.fragment_menu, container, false);
        final Activity activity = getActivity();
        final MenuActivity menuAct = new MenuActivity();
        final MenuViewModel viewModel = ViewModelProviders.of(this, new MenuViewModelFactory(activity.getApplication(), MenuActivity.ResID)).get(MenuViewModel.class);
        viewModel.getAllMenuTitles().observe(this, new Observer<String[]>() {
            @Override
            public void onChanged(String[] strings) {
                final Spinner spinner = rootView.findViewById(R.id.spinner);
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), R.layout.support_simple_spinner_dropdown_item, strings);
                adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
                spinner.setAdapter(adapter);

                spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                        menuAct.removeAllTabs();
                        SubMenuViewModel vm = ViewModelProviders.of(getParentFragment(), new SubMenuViewModelFactory(menuAct.getApplication(), i)).get(SubMenuViewModel.class);
                        vm.getSubMenus().observe(getActivity(), new Observer<String[]>() {
                            @Override
                            public void onChanged(@Nullable String[] strings) {
                                menuAct.populateTabs(strings);
                            }
                        });
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> adapterView) {

                    }
                });
            }
        });

        return rootView;
    }

0 个答案:

没有答案