1

Im having a issue I dont know how to resolve.

I have a fragment with a editText and a button. The button launches a fragment map like this:

public void onClick(View view) {
        //Fragment fragment = null;

        switch (view.getId()) {
            case R.id.SearchButton:

                Home activity = (Home) getActivity();
                if(activity != null)activity.openMapFragment();
                break;
        }

and the function openMapFragment():

public void openMapFragment(){
        Fragment fragment = new gMapFragment();
        replaceFragment(fragment);
    }

How would i do to send the text inserted on editText field as a address to look for on map fragment?

Capie
  • 976
  • 1
  • 8
  • 20

1 Answers1

1

You should use bundle to pass data to a fragment :

public void openMapFragment(String args){
    Fragment fragment       = new gMapFragment();
    Bundle bundle           = new Bundle();
    bundle.putString("foo", args);
    fragment.setArguments(bundle);
    replaceFragment(fragment);
}

And to retrieve data :

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //...
    String foo = getArguments() != null ? getArguments().getString("foo") : "";
    //...
}
Yoleth
  • 1,269
  • 7
  • 15
  • and once I do that, how would I recover the parameters on the fragment (`"foo"` in this case) ? EDIT: I already saw how. Thanks. – Capie Jan 17 '17 at 15:12
  • Any idea how to fix the NullPointerException? – Capie Jan 17 '17 at 15:49
  • fixed it. `this.getArguments().getString("foo");` and on the activity: `fragment.setArguments(bundle);` – Capie Jan 17 '17 at 15:55