0

I'm trying to pass a text field from an activity to a fragment, using this code:

EditText textPlayer1;

public void goToSinglePlayer() {
    Intent intent = new Intent(this, ActivitySinglePlayer.class);
    String player1Name = textPlayer1.getText().toString();
    Bundle bundle = new Bundle();
    bundle.putString(player1Name, "player1Name");
    intent.putExtras(bundle);
    startActivity(intent);
}

I want a player to enter the text, and then pass the name to the fragment. When I recieve the bundle, I have this code:

   public SinglePlayerGameFragment() {
    // Required empty public constructor
}

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

@Override
public View onCreateView
        (LayoutInflater inflater,
         ViewGroup container,
         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_single_player_game, container, false);
    TextView player1Name = view.findViewById(R.id.player1Name);
    String name = (getActivity().getIntent().getExtras().getString("player1Name"));
    player1Name.setText(name);
    return view;
}

This gives me the error:

Caused by: android.view.InflateException: Binary XML file line #13: Binary XML file line #13: Error inflating class fragment
               Caused by: android.view.InflateException: Binary XML file line #13: Error inflating class fragment
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

I've been racking my brain trying to figure this one out, but I'm stuck. Anyone have an idea?

Thank you in advance.

kveola92
  • 69
  • 4
  • 2
    Does `fragment_single_player_game.xml` contains a `TextView` with `player1Name` as `id` ? – B.M Apr 16 '18 at 09:38
  • I think your problem lies in how Activity `ActivitySinglePlayer` inflates the fragment. – Gotiasits Apr 16 '18 at 09:54
  • It is not what you asked for, but additionally the line `bundle.putString(player1Name, "player1Name");` seems wrong. The first argument is the key, so you need to call `bundle.putString("player1Name", player1Name);` to be able to retrieve it later via `getString("player1Name")` – martink Apr 16 '18 at 09:59
  • @B.M no, it does not. – kveola92 Apr 16 '18 at 10:10
  • @martink oh, I see, thank you :) I fixed that now – kveola92 Apr 16 '18 at 10:10
  • 1
    The `textview` with the id `player1Name` should be defined on `fragment_single_player_game.xml`, that's where the error comes from – B.M Apr 16 '18 at 10:14

0 Answers0