This post is not to explain about android tabbed activity or fragments.
We are publishing the issues we have faced in our learning process with Tabbed activity in android and Fragments.
How to call fragment method from Main Activity class ?
We have created a simple tabbed activity with three tabs. All the tabs are linked to a custom fragment.
The fragments are managed by FragmentPagerAdapter and Fragment class for loading the fragments in respective tabs.
Problem:
Main Activity has a menu button "tab1", "tab2".
Each fragment class (Tab1, Tab2, Tab3) has a function.
When a user clicks menu button "tab1", Main Activity calls the function in Tab1 fragment.
Error:
Error 1 : android.content.context android.content.context.getapplicationcontext()' on a null object reference
Error 2 : Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
Root cause:
FragmentPageAdapter does not use the ID or TAG defined by user for the Fragments.
The Fragment ID is automatically created by FragmentPageAdapter internally.
So, when MainActivity uses the instance of the Tab1 and calls the function, it throws an null object reference.
Solution:
In your Main Activity, declare the Tab classes like below.
MainTab1 maintab1; MainTab2 maintab2; MainTab3 maintab3;
In Main Activity, OnCreate method, the code should look like below, use instantiateItem method
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container); mViewPager.setAdapter(mSectionsPagerAdapter); TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(mViewPager);
mSectionsPagerAdapter.startUpdate(mViewPager); maintab1 = (MainTab1) mSectionsPagerAdapter.instantiateItem(mViewPager,0);
maintab2 = (MainTab2) mSectionsPagerAdapter.instantiateItem(mViewPager,1); maintab3 = (MainTab3) mSectionsPagerAdapter.instantiateItem(mViewPager,2); mSectionsPagerAdapter.finishUpdate(mViewPager);
That's it.
Now, you can call any function in your fragments as below.
maintab1.tab1_function(); maintab2.tab2_function();
