-4

My app works with a TabLayout (and so a ViewPager).

I have a Fragment A and a Fragment B. My goal is to recover data from my EditTexts of Fragment A to, obviously, print and works with them in my Fragment B.

For this, I use an interface named ButtonCliked, but seems not to work well. Did I forgot something ?

TabFragment.java (use to manage my fragments)

public class TabFragment extends Fragment implements EquationsCalculFragment.ButtonClicked {


    public static TabLayout tabLayout;
    public static ViewPager viewPager;
    public static int int_items = 3 ;

    @Override
    public void sendResultats(float a, float b) {
        EquationsResultatFragment fragRes = (EquationsResultatFragment) getFragmentManager().findFragmentById(R.id.Equa_2nd_ResLayout);
        fragRes.getResultat(a, b);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        /**
         *Inflate tab_layout and setup Views.
         */
        View x =  inflater.inflate(R.layout.tab_layout,null);
        tabLayout = (TabLayout) x.findViewById(R.id.tabs);
        viewPager = (ViewPager) x.findViewById(R.id.viewpager);

        /**
         *Set an Apater for the View Pager
         */
        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));

        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.setupWithViewPager(viewPager);
            }
        });

        return x;

    }

    class MyAdapter extends FragmentPagerAdapter{

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        /**
         * Return fragment with respect to Position .
         */

        @Override
        public Fragment getItem(int position)
        {
            switch (position){
                case 0 : return new EquationsCalculFragment();
                case 1 : return new EquationsResultatFragment();
                case 2 : return new EquationsInfosFragment();
            }
            return null;
        }

        @Override
        public int getCount() {

            return int_items;

        }

        /**
         * This method returns the title of the tab according to the position.
         */

        @Override
        public CharSequence getPageTitle(int position) {

            switch (position){
                case 0 :
                    return "Calcul";
                case 1 :
                    return "Résultats";
                case 2 :
                    return "Infos";
            }
            return null;
        }
    }
}

Fragment A : EquationsCalculFragment.java

public class EquationsCalculFragment extends Fragment {

    private String aS;
    private String bS;

    private EquationsCalculFragment.ButtonClicked callEqua2ndRes;

    public interface ButtonClicked {
        void sendResultats(float a, float b);
    }

    private ViewPager viewPager;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

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

        viewPager = (ViewPager) getActivity().findViewById(R.id.viewpager);

        final EditText champ_a = (EditText) view.findViewById(R.id.equa_2nd_a);
        final EditText champ_b = (EditText) view.findViewById(R.id.equa_2nd_b);

        Button button = (Button) view.findViewById(R.id.btn_equations_resultats);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bS = champ_b.getText().toString();
                aS = champ_a.getText().toString();
                callEqua2ndRes.sendResultats(Float.parseFloat(aS), Float.parseFloat(bS));
                viewPager.setCurrentItem(1, true);
            }
        });
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            if (context instanceof EquationsCalculFragment.ButtonClicked) {
                callEqua2ndRes = (EquationsCalculFragment.ButtonClicked) context;
            }
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + " must implement ButtonClicked");
        }
    }

    @Override
    public void onDetach() {
        callEqua2ndRes = null;
        super.onDetach();
    }
}

Fragment B : EquationsResultatFragment.java

public class EquationsResultatFragment extends Fragment {
    private TextView results;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_equations_resultat, container, false);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        results = (TextView) getView().findViewById(R.id.equa_2nd_resultat);
    }

    public void getResultat(float a, float b) {
        results.setText(String.valueOf((a*a)+(2*a*b)+(b*b)));
    }
}

Is there anything I'm doing wrong ?

Slabre
  • 149
  • 1
  • 10
  • Please add only the valid question and data, so it can be easy to understand and to answered. – A-Droid Tech Apr 14 '16 at 12:17
  • not sure, but I think you are passing incorrect `position` parameter to your `Fragment getItem(int position)` or in `getPageTitle()` method. You are returning null there. It is not a good practice. If there is an incorrect argument supplied, better `throw new IllegalArgumentException()`. –  Apr 14 '16 at 12:18
  • @Exaqt Sorry, it doesn't help me to solve my problem. – Slabre Apr 14 '16 at 12:27
  • @A-DroidTech if I remove something, I think it wiil be harder to understand – Slabre Apr 14 '16 at 12:28
  • @slabre : You got incompatible error because get item is a method of MyAdapter and TabFragment implements interface and not MyAdapter :) So what to do simply say calculationFragment.callEqua2ndRes = TabFragment.this; thats all buddy :) Please check my updated answer :) – Sandeep Bhandari Apr 14 '16 at 12:28
  • @Salbre : Lemme know if you still have a issue :) Shouldn't have one though :) – Sandeep Bhandari Apr 14 '16 at 12:30
  • @Salbre : I updated my answer buddy :) have a look at it :) again might have syntactic error as I dont have system with me now :) Idea is to check if fragment is loaded or not ? if not programmatically scroll to index 1 so that fragment gets loaded and then call its method :) Hope it helps :) – Sandeep Bhandari Apr 14 '16 at 12:56
  • @Salbre : you still having issue dudde ??? – Sandeep Bhandari Apr 14 '16 at 12:59

2 Answers2

0

Issue is you have declared an interface in EquationsCalculFragment but never initialied it :)

So here is what you can do :)

In EquationsCalculFragment, change

private EquationsCalculFragment.ButtonClicked callEqua2ndRes;

to

public EquationsCalculFragment.ButtonClicked callEqua2ndRes;

and in TabFragment, getItem methods case 0, make this change :)

case 0 : EquationsCalculFragment calculationFragment = new EquationsCalculFragment();
         calculationFragment.callEqua2ndRes = TabFragment.this;
         return calculationFragment;

Should solve your issue :) Hope my answer helped :)

P.S : Code provided above is to explain the concept and not for copy paste, might contain syntactic error :) If contains please modify and use it :D

Sandeep Bhandari
  • 19,999
  • 5
  • 45
  • 78
  • please leave comment when you down vote :) helps understanding my mistake :D – Sandeep Bhandari Apr 14 '16 at 12:24
  • I've made the change. I just have an incompatibility of types in my case 0, on the line `calculationFragment.callEqua2ndRes = this;`. Android Studio tells me : Required: EquationsCalculFragment.ButtonClicked and Found: TabFragment.MyAdapter. I do not see why – Slabre Apr 14 '16 at 12:24
  • @Salbre : Thats fisshy :P lemme have a look again :) give me a minute :) – Sandeep Bhandari Apr 14 '16 at 12:25
  • @Salbre : can you please check with updated answer of mine :) – Sandeep Bhandari Apr 14 '16 at 12:27
  • Unfortunately this creates other NullPointerExceptions. Like at `fragRes.getResultat(a, b);` at the beginning of TabFragment.java – Slabre Apr 14 '16 at 12:32
  • @Salbre : I answerred only for interface being null :) lemme have a look at the issue though :) I believe your interface issue is solved :D – Sandeep Bhandari Apr 14 '16 at 12:34
  • @Salbre : You are getting null pointer exception because your EquationsResultatFragment fragment is not loaded :) What exactly are you trying to do ?? on getting result back from fragment EquationsCalculFragment do you want to load fragment and show results there ??? – Sandeep Bhandari Apr 14 '16 at 12:39
  • Actually, in EquationsCalculFragments, I want to recover the values of my EditTexts. Then, in my EquationsResultatFragment (`getResultat(..)` method), I have a mathematical operation and next the results are printed in a TextView. – Slabre Apr 14 '16 at 12:45
  • @slabre : But when will EquationsCalculFragments gets loaded?? will user swipe your FragmentPagerAdapter or when user taps on button you want to load EquationsCalculFragments programmatically ?? :D – Sandeep Bhandari Apr 14 '16 at 12:49
  • When I go to the TabFragment, EquationsCalculFragment become loaded automatically (I think) because case 0 correspond to the first tab. So, even if the button is not clicked, the user can swipe to the EquationsResultatFragment. Also, when the user click on the button, he's automatically redirected on EquationsResultatFragment. – Slabre Apr 14 '16 at 12:56
  • Thank you for your edit! But, the error always occurs at the same line, I mean at `fragRes.getResultat(a, b);` in the `else`. This happens when I click on the button. – Slabre Apr 14 '16 at 13:00
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/109156/discussion-between-sandeep-bhandari-and-slabre). – Sandeep Bhandari Apr 14 '16 at 13:02
0

I thinkthe NPE is because you try to find the fragment with it's id, but you supply I guess the id of the ViewPager? Try finding it by tag, it should look something like this:

int position;
getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.yourViewPagerIdGoesHere + ":" + position);

Where the position is the pos of your targeted fragment just like in the adapter's public Fragment getItem(int position) method

datiKaa
  • 326
  • 2
  • 15