androidandroid-fragmentsandroid-viewpagertabbed-viewandroid-tabbed-activity

How to call a fragment method from an activity in android?


I'm having a tabbed View, and a Floating Action Button on my Main Activity. Whenever I click on the Floating Action Button, I want to call a method that is present in my fragment's code. I tried many things, but it is saying that

Attempt to invoke virtual method 'void com.shyamzawar.makeMyResume.fragments.EducationalDetailsFragment.showChangeLangDialog()' on a null object reference

Here's my code for UserDetailsActivity :

public class UserDetailsActivity extends AppCompatActivity {

private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter adapter;

private int currentPage;

private FloatingActionButton fab;

private int readFileRequestCode;

private int[] tabIcons = {
        R.drawable.ic_account_circle_white,             //0 Personal Details
        ...
        R.drawable.ic_create_white_36dp,                //7 Declaration
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_details);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    //getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    //Set Title according to the user clicked
    String name = "Shyam Zawar";
    this.setTitle(name+"'s Profile");

    fab = (FloatingActionButton) findViewById(R.id.fab);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);
    viewPager.addOnPageChangeListener(new DetailOnPageChangeListener());



    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    setupTabIcons();

    fab.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            if (currentPage>0)
            {
                switch (currentPage)
                {
                    case 1:
                        FragmentManager manager = getSupportFragmentManager();
                        EducationalDetailsFragment educationalDetailsFragment = (EducationalDetailsFragment) manager.findFragmentById(R.id.EduFragment);
                        educationalDetailsFragment.showChangeLangDialog();
                        break;
                }
            }
        }
    });
}


private void setupTabIcons()
{
    tabLayout.getTabAt(0).setIcon(tabIcons[0]);
    ...
    tabLayout.getTabAt(7).setIcon(tabIcons[7]);
}

private void setupViewPager(ViewPager viewPager)
{
    adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new PersonalDetailsFragment(), " PERSONAL DETAILS");            //0
    ...
    adapter.addFrag(new DeclarationFragment(), " DECLARATION");                     //7
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position)
    {
        return mFragmentList.get(position);
    }

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

    public void addFrag(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
  }
}

Here is the code for EducationalDetailsFragment.java

public class EducationalDetailsFragment extends Fragment{

private FloatingActionButton fab;
private TextView TextViewEduDetails;

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

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

    View view = inflater.inflate(R.layout.fragment_educational_details, container, false);

    TextViewEduDetails = (TextView) view.findViewById(R.id.TextViewEduDetails);

    return view;
}

public void setData(String stringData)
{
    TextViewEduDetails.setText(stringData);
}

public void showChangeLangDialog() {
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
    LayoutInflater inflater = getActivity().getLayoutInflater();
    final View dialogView = inflater.inflate(R.layout.educational_details_dialog, null);
    dialogBuilder.setView(dialogView);

    dialogBuilder.setTitle("Educational Details");
    dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {}
    });
    dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {}
    });
    AlertDialog b = dialogBuilder.create();
    b.show();
}

}

Solution

  • You can globally declare your educationFragment

    private EducationalDetailsFragment mEducationalDetailsFragment;
    
    
    //in your setupViewPager() method
    mEducationalDetailsFragment = new EducationalDetailsFragment();
    adapter.addFrag(mEducationalDetailsFragment , "Whatever the Name");
    
    
    onYourFabClickListerner(){
         call the method by using mEducationalDetailsFragment
    }