Search code examples
androidtabsandroid-viewpager

Tab Item Selection Programmatically


I am trying to programmatically set tab selection for my tabLayout. I keep getting a null pointer.

 firebaseFirestore.collection("Categories")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                Log.d(TAG, document.getString("title") + " => " + document.getData());
                                tabLayout.addTab(tabLayout.newTab().setText(document.getString("title")));
                                tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
                                tabLayout.getTabAt(5).select();
                                final CategoriesPagerAdapter categoriesPagerAdapter = new CategoriesPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
                                viewPager.setAdapter(categoriesPagerAdapter);
                            }
                        } else {
                            Log.d(TAG, "Error getting documents: ", task.getException());
                        }
                    }
                });

Why does getTabAt(5).select keep returning null?


Solution

  • The problem is that you are trying to select a tab that hasn't been added to the TabLayout. You are calling this...

    tabLayout.getTabAt(5).select();
    

    after this...

    tabLayout.addTab(tabLayout.newTab().setText(document.getString("title")));
    

    try moving the call to select out of the for loop. Also, be aware that the documentation explicitly says the following about the select method...

    Select this tab. Only valid if the tab has been added to the action bar.

    So, if the TabLayout hasn't been added to the action bar it will do nothing.

    Another issue is that you are re-creating and setting the viewpager's adapter on every single iteration of the for loop.

    My advice, please stop working on this app until you are sure what you are doing. You have more than one obvious bugs in the code snippet you posted