-3

How do I pass the data from one fragment to another when button is pressed from the activity in which view pager is initiate.

activity_main.xml

<android.support.v4.view.ViewPager
        android:elevation="@dimen/activity_horizontal_margin"
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v4.view.ViewPager>


    <Button
        android:id="@+id/btn_next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:background="@null"
        android:text="@string/next"
        android:textColor="@android:color/white" />

when I press btn_next then next fragment will show. How will I fetch the data from previous fragment to current fragment?

I have one fragment:

public class BpDetails extends Fragment {

        private int page;

    private EditText systolic;
    private EditText diastolic;

    // newInstance constructor for creating fragment with arguments
        public static BpDetails newInstance(int page) {
            BpDetails fragmentFirst = new BpDetails();
            Bundle args = new Bundle();
            args.putInt("someInt", page);
            fragmentFirst.setArguments(args);
            return fragmentFirst;
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            page = getArguments().getInt("someInt", 0);
        }


        // Inflate the view for the fragment based on layout XML
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            final View view = inflater.inflate(R.layout.bp_details, container, false);

            Log.i("View ",view.toString());


            systolic =(EditText) view.findViewById(R.id.systolic);
            diastolic =(EditText) view.findViewById(R.id.diastolic);


            return view;
        }
}

and page adapter

public static class MyPagerAdapter extends FragmentPagerAdapter {
        private static int NUM_ITEMS = 4;
        private static int mSelectedPosition;

        public MyPagerAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
            //mSelectedPosition=selectedPosition;
        }

        // Returns total number of pages
        @Override
        public int getCount() {
            return NUM_ITEMS;
        }

        // Returns the fragment to display for that page
        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0: // Fragment # 0 - This will show FirstFragment
                    return BasicDetails.newInstance(0);
                case 1:
                    return BpDetails.newInstance(1);
                case 2:
                    return BslDetails.newInstance(2);
                case 3:
                    return Summary.newInstance(3);

                default:
                    return null;
            }
        }

    }

For just clarification I want to access the systolic value in another fragment when user click on btn_next in activity.

Update:

I have try to do this way in Fragment.

  public String getSystolic(){

            return this.systolic.getText().toString();

        }

then when user click on next button

Fragment bpFragment=adapterViewPager.getItem(vpPager.getCurrentItem());

                    if (bpFragment instanceof BpDetails){

                        System.out.println("Current item is "+vpPager.getCurrentItem());

                        Fragment f=adapterViewPager.getInstantiatedFragment(vpPager.getCurrentItem());


                       BpDetails fr = (BpDetails)adapterViewPager.getItem(vpPager.getCurrentItem());

                        String systolicString = fr.getSystolic();

                        Log.i("Systolic is ",systolicString);
                    }
Ankur Khandelwal
  • 269
  • 1
  • 4
  • 17
  • http://stackoverflow.com/questions/16036572/how-to-pass-values-between-fragments refere this link you can better understand – Krishna Kachhela Feb 21 '17 at 12:35
  • http://stackoverflow.com/a/39252949/4387357 – Jerin A Mathews Feb 21 '17 at 12:40
  • @KrishnaJ the link that you have posted is talking about send data from one fragment to another when I press button in one fragment. In my case there is no trigger point in fragment. I need to do it through main activity btn only. – Ankur Khandelwal Feb 21 '17 at 12:40

4 Answers4

0

Activity :

FirstFragment.newInstance(0, "Page # 1");

Fragments:

public static FirstFragment newInstance(int page, String title) {
    FirstFragment fragmentFirst = new FirstFragment();
    Bundle args = new Bundle();
    args.putInt("someInt", page);
    args.putString("someTitle", title);
    fragmentFirst.setArguments(args);
    return fragmentFirst;
}

For More Details Refer link:https://guides.codepath.com/android/ViewPager-with-FragmentPagerAdapter

Vadivel
  • 780
  • 1
  • 6
  • 21
0

putArguments on OnScrollChangeListener and getArguments on other fragment.

or you can also use

LocalBroadCast to send data from one fragment to another in ViewPager.

Learn Pain Less
  • 2,274
  • 1
  • 17
  • 24
  • if i use the first method. then how will I get the id of the fragment in the view pager activity. – Ankur Khandelwal Feb 21 '17 at 12:46
  • simply get fragment from ViewPagerAdapter at position. – Learn Pain Less Feb 21 '17 at 12:47
  • I have updated my question with the adapter and fragment. Can you help with me the code. I am not getting. Sorry for that. – Ankur Khandelwal Feb 21 '17 at 12:57
  • in your activity you can get fragment from object of your Adapter class. to get fragment you can use this method, adapter.getItem(position); – Learn Pain Less Feb 21 '17 at 13:00
  • if you are getting any problem then you can use second method also , which is best way. just sendBroadCast on button click and message will be received on other fragment – Learn Pain Less Feb 21 '17 at 13:02
  • Fragment fragment=adapterViewPager.getItem(prevPage); if (fragment.getClass().equals(BpDetails.class)){ } I have try this but now how will I get the id of edittext. i.e. in my case I required systolic – Ankur Khandelwal Feb 21 '17 at 13:13
  • create any public method to set value in that fragment where you want to send data. after getting fragment from adapter, you can call public method of that fragment for setting value, before calling that method apply a check if(fragment instanceOf YourFragment) { ((YourFragment)fragment).setData("Your data"); } – Learn Pain Less Feb 21 '17 at 13:16
  • I think you understand wrongly. I need to fetch the data from previous fragment in the current fragment, not to set the data. – Ankur Khandelwal Feb 21 '17 at 13:25
  • then you can create getter method on old fregment and get value in new fragment from that getter method (same way as i said about setting data) – Learn Pain Less Feb 22 '17 at 05:29
  • Hey, I have tryied this way but got the nullpointerexception while calling the getter method inside the next onClick method. @LearnPainLess – Ankur Khandelwal Feb 22 '17 at 05:33
0

Implement the public getData method in source fragment and setData method in Target fragment.

On next button click, find currently visible fragment and get data from that fragment getSupportFragmentManager().findFragmentByTag("android:switcher:" + getViewPager().getId() + ":"+ fragmentPagerAdapter.getItemId(position));

after that move to next fragment and onPageSelected method find next visible fragment and set data their

  • since the target fragment contains set text so there is no certain way I can call the setData method. If I call it when user touch/click the edit text then most probably I will not get the current value. @Hiren. are you got my problem? – Ankur Khandelwal Feb 21 '17 at 13:54
  • @AnkurKhandelwal first get systolic value from BpDetails fragment, after that move to next fragment using ViewPager setCurrentItem method. In onPageSelected method get next fragment instance and set value their – Hiren Patel Feb 21 '17 at 14:01
  • That's the problem I am not able to get the systolic value. Since there is only edittext, user may or may not fill the data. I can only get the systolic data when user press the next button but this outside of fragment so can't access the systolic variable. @Hiren is there any way to access it? – Ankur Khandelwal Feb 21 '17 at 15:25
  • @Ankur To get value of systolic implement public getter method inside BpDetails fragment, inside getter method return edit text value using edit text gettext method. Next, in on next button click get instance of BpDetails fragment using getActivity().getFragmentManager().findFragmentById(fragmentContainerId);// fragmentContainerId is your viewpager id. Here you will get instance of BpDetails fragment, using that you can get access of get sysmbolic public method implemented initially – Hiren Patel Feb 22 '17 at 03:16
  • getActivity().getFragmentManager().findFragmentById(fragment‌​ContainerId); I am not able to write this line in onClick of next button. Since the view pager is defined in activity so I can't use getActivity(). But I got the fragment in next Onclick() method using BpDetails fr = (BpDetails)adapterViewPager.getItem(vpPager.getCurrentItem()); but when I calling the public getter method then I am getting the nullPointerException because I think when I call getItem() method it create again a fragment with null data. – Ankur Khandelwal Feb 22 '17 at 05:13
  • @AnkurKhandelwal Replace BpDetails fr = (BpDetails)adapterViewPager.getItem(vpPager.getCurrentItem()‌​) with BpDetails fr = (BpDetails)getFragmentManager().findFragmentById(fragment‌​‌​ContainerId); //fragment‌​‌​ContainerId would be your viewpager id – Hiren Patel Feb 22 '17 at 05:31
  • BpDetails fr=(BpDetails)getFragmentManager().findFragmentById(R.id.viewPager); I have done that. But getting error cannot cast android.app.Fragment to package_name.BpDetails. – Ankur Khandelwal Feb 22 '17 at 05:36
  • @AnkurKhandelwal Replace BpDetails fr = (BpDetails)adapterViewPager.getItem(vpPager.getCurrentItem()‌​) with BpDetails fr = (BpDetails)getSupportFragmentManager().findFragmentByTag( "android:switcher:" + getViewPager().getId() + ":" + fragmentPagerAdapter.getItemId(position)); – Hiren Patel Feb 22 '17 at 05:37
0

The most simple way to do this is use the EventBus library.

kostyabakay
  • 1,649
  • 2
  • 21
  • 32