How to pass a string between fragments in a viewpager

11,034

Solution 1

So i found the solution, the implementation is correct, the only thing that I should do the treatement I want in the method on the second fragment and that's it !

Solution 2

You're obviously using ViewPager and you can take advantage of it. You can add a tag to a ViewPager like this:

Activity:

pager.setTag("some text");  // pager is a ViewPager object

Then you can get this data via ViewGroup in a fragment like this:

Fragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view =  inflater.inflate(R.layout.fragment_main, container, false);

    String result = container.getTag().toString();
    // do something with the result

    return view;

You can also setTag() to the container in the fragment.

This is the cleanest solution I found for sending data among fragments and their mother activity. Another solution (not mentioned here so far) is sending data through SharedPreferences, but I would suggest using tags if possible.

Share:
11,034
user2137817
Author by

user2137817

Updated on June 06, 2022

Comments

  • user2137817
    user2137817 almost 2 years

    I'm trying to pass a string between two fragments in a viewpager but I didn't found the right way to do it. Here is my code so far :

    public class MyFragmentPagerAdapter extends FragmentPagerAdapter{
    
        final int PAGE_COUNT = 6;
    
        /** Constructor of the class */
        public MyFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }
    
        /** This method will be invoked when a page is requested to create */
        @Override
        public Fragment getItem(int arg0) {
    
    
            switch (arg0) {
            case 0:
                return new MyFragment();
            case 1:
                return new part2();
            case 2:
                return new Part3();
            case 3:
                return new Part4();
            case 4:
                return new Part5();
            case 5:
                return new Part6();
            default:
                return null;
            }
        }
    
        /** Returns the number of pages */
        @Override
        public int getCount() {     
            return PAGE_COUNT;
        }
    
        @Override
        public CharSequence getPageTitle(int position) {        
            return "Page #" + ( position + 1 );
        }
    
    
    
    
    
    }
    
    public class MainActivity extends FragmentActivity {
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            /** Getting a reference to the ViewPager defined the layout file */        
            ViewPager pager = (ViewPager) findViewById(R.id.pager);
    
            /** Getting fragment manager */
            FragmentManager fm = getSupportFragmentManager();
    
            /** Instantiating FragmentPagerAdapter */
            MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(fm);
    
            /** Setting the pagerAdapter to the pager object */
            pager.setAdapter(pagerAdapter);
    
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.activity_main, menu);
            return true;
        }
    }
    

    I'm not using tabs with the viewpager. What should I write in the fragments?

    UPDATE : I tried to implement an interface like suggested in the answers :

    public interface OnTogglePressListener {
        public void onTogglePressed(String msg);
    }
    

    On the first fragment :

    @Override
    public void onAttach(Activity activity) {
            // TODO Auto-generated method stub
            try {
                buttonListener = (OnTogglePressListener) getActivity();
            } catch (ClassCastException e) {
                throw new ClassCastException(activity.toString() + " must implement onTogglePressed");
            }
            super.onAttach(activity);
        }
    
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            buttonListener.onTogglePressed("Off");
    ... }
    

    On the second fragment :

    public String getEtat(String etat)
        {   state =etat;
            return etat;
    
        }
    

    On the main activity :

    public void onTogglePressed(String etat)
        {
            Part5 p = (Part5)getSupportFragmentManager().findFragmentById(R.layout.frag_2);
            p.getEtat(etat);
    
        }
    

    But I got a NullPointerException everytime.

    • Arash GM
      Arash GM over 10 years
      did you initialize your Interface? try make an object from your Interface then instantiate your interface object on onActivityCreated() callback function like : InterfaceInstance = (onTogglePressListener)getActivity();
  • Arash GM
    Arash GM over 10 years
    it works but it's not the best way,this solution won't work on ViewPager!
  • tread
    tread almost 9 years
    Terrible Answer, consider revising and changing the selected answer