0

Hello how can I pass two parameters from a fragment to an activity? I tried to do this but I can't. I got only the ref in the TextView editRef but the TextView et_login is empty

public class ResultFragmentC  extends Fragment implements ListView.OnItemClickListener {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootview = inflater.inflate(R.layout.fragment_result, container, false);
        et_login = (TextView) rootview.findViewById(R.id.et_login);
        Intent intent = getActivity().getIntent();
        String log = intent.getStringExtra("login");
        et_login.setText(log);
......

}
......

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(getActivity().getApplicationContext(), ViewResult.class);
            HashMap<String, String> map = (HashMap) parent.getItemAtPosition(position);
            String tid = map.get("ref");
            intent.putExtra("ref", tid);
            String tid2 = map.get("log");
            intent.putExtra("log", tid2);
            startActivity(intent);
        }

ViewResult.java

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_result);
        Intent intent = getIntent();
        layout=(LinearLayout) findViewById(R.id.layout);
        String ref2 = intent.getStringExtra("ref");
        et_login = (TextView) findViewById(R.id.et_login);
        String log = intent.getStringExtra("log");
        et_login.setText(log);
        editRef = (TextView) findViewById(R.id.editRef);
        editRef.setText(ref2);
}
clara
  • 11
  • 1
  • 6

1 Answers1

0

Carefully check you are using the same keys for the intents.

Intent intent = getActivity().getIntent();
String log = intent.getStringExtra("login");

Is not the same as

Intent intent = getIntent();
String log = intent.getStringExtra("log");

What you've shown in ViewResult.java should work with what you have in onItemClick assuming map.get() isn't returning you null.

It should be mentioned though, that using the Activity intent is not how you give parameters to Fragments. Please see Best practice for instantiating a new Android Fragment.

Community
  • 1
  • 1
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • I have a login form. so I want to display the login in all the fragments and activities. In the first fragment I have a listview with the login but when I click in the listview the login wasn't displayed in the activity – clara May 31 '16 at 20:08
  • Well, like I said, `ViewResult.java` should work and display the data unless you ended up putting null in with `intent.putExtra("log", tid2);` – OneCricketeer May 31 '16 at 20:13
  • Also, are `fragment_result.xml` and `view_result.xml` practically the same thing? They both have a `@+id/et_login`? – OneCricketeer May 31 '16 at 20:15