使用Intent+Bundle的java Android Studio NullpointerException
我正在尝试使用以下代码将文本字段从活动传递到片段:
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);
}
我希望玩家输入文本,然后将名称传递给片段。当我收到捆绑包时,我有以下代码:
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;
}
这给了我一个错误:
Caused by: 安卓.view.InflateException: Binary XML file line #13: Binary XML file line #13: Error inflating class fragment
Caused by: 安卓.view.InflateException: Binary XML file line #13: Error inflating class fragment
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void 安卓.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
我一直在绞尽脑汁想弄明白这一点,但我被卡住了。有人有主意吗
先谢谢你
共 (0) 个答案