简体   繁体   中英

Setting and getting fragment by tag always return null

So am trying to make 2 fragments communicate over their parent activity. I implement interface and callback functions like this :

public class FormFragment extends Fragment {

    private EditText mStudentTextField;
    private EditText mStudentIndexField;
    private Button mSubmit;
    private String mStudentName;
    private int mStudentIndex;
    SendData sd;

    interface SendData {

        public void send(String msg);
    }

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

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

        mStudentTextField = (EditText) view.findViewById(R.id.input_name);
        mStudentIndexField = (EditText) view.findViewById(R.id.input_index);
        mSubmit = (Button) view.findViewById(R.id.submit_button);

        mSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mStudentName = mStudentTextField.getText().toString();
                // mStudentIndex =
                // Integer.parseInt(mStudentIndexField.toString());

                sd.send(mStudentName);
                HomeFragment homeFragment = new HomeFragment();
                FragmentTransaction ft = getFragmentManager()
                        .beginTransaction();
                ft.replace(R.id.formFragment_Container, homeFragment,
                        "HOME_FRAGMENT").commit();
            }
        });

        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            sd = (SendData) activity;
        } catch (ClassCastException c) {

            throw new ClassCastException(activity.toString()
                    + "Must implement send() method");
        }
    }
}

This is like a middle ground. FormFragments gets attached 1st in MainActivity and gets called first. Next, I take values from EditText and on button click I call callback function that gets 2 values (name and index) to MainActivity. So getting data from FormFragment to Activity works.

Here's my HomeFragment that should get data from MainActivity and display them on proper TextFields.

HomeFragment controller :

public class HomeFragment extends Fragment {

    private TextView mName;
    private TextView mIndex;

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

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

        mName = (TextView) view.findViewById(R.id.student_name);
        mIndex = (TextView) view.findViewById(R.id.student_index);

        return view;

    }

    public void getData(String msg) {

        mName.setText(msg);
    }
}

So, you see. It's simple. Just get data from args and do something with it. Now, in MainActivity, I get a problem I can't seem to solve despite surfing Stack Overflow and reading documentation on android developers and github.

Take a look at my MainActivity :

public class MainActivity extends Activity implements FormFragment.SendData {

    private String test;
    HomeFragment hf;

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

        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        FormFragment formFragment = new FormFragment();

        ft.add(R.id.formFragment_Container, formFragment, "FORM_FRAGMENT")
                .addToBackStack(null).commit();

        hf = (HomeFragment) getFragmentManager().findFragmentByTag(
                "HOME_FRAGMENT"); // get a reference to a home fragment

    }

    @Override
    public void send(String msg) {

        hf.getData(msg);
    }
}

Problem is that hf is null reference , so when I call getData() it crashes, obviously. I believe that I've properly set TAG names for both fragments, for first fragment in add(), and for second in replace(). What could be the reason behind such behavior. Thanks

The fragment has not been added right after ft.add(R.id.formFragment_Container,formFragment, "FORM_FRAGMENT").addToBackStack(null).commit(); or even after calling fm.executePendingTransactions() , because you only add it to the fragment manager after a button has been clicked in the mSubmit buttons OnClickListener .

You could include the home fragment instance in a callback. Or you could add the fragment to the fragmentManager hidden: ft.replace(R.id.formFragment_Container, homeFragment, "HOME_FRAGMENT").hide(homeFragment).commit(); and only show it when the button is pressed. But I'd suggest you think a bit about your design there are probably much better options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM