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.