Android Studio中使用Intent+Bundle传递数据时触发空指针异常
嘿,我看到你在从Activity往Fragment传递玩家名称时碰到了空指针异常,咱们一步步来排查解决问题~
首先,最核心的错误:Bundle存值的参数顺序搞反了!
你写的这行代码把键和值的位置弄颠倒了:
bundle.putString(player1Name, "player1Name");
putString的正确用法是第一个参数是固定的键名(用来后续取值),第二个参数是要传递的实际值。所以这行应该改成:
bundle.putString("player1Name", player1Name);
完整修正后的Activity传值代码
先把发送方的代码捋顺,还要确保textPlayer1已经完成初始化(不然这里就会先出空指针):
EditText textPlayer1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.your_activity_layout); // 别忘了初始化EditText!这步很容易漏 textPlayer1 = findViewById(R.id.your_edittext_id); } 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); }
然后,在ActivitySinglePlayer中把Bundle传给Fragment
假设你要在这个Activity里加载目标Fragment,需要把收到的Bundle传递给Fragment:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_single_player); // 先拿到从之前Activity传过来的Bundle,记得判空 Bundle receivedBundle = getIntent().getExtras(); if (receivedBundle != null) { // 初始化你的Fragment实例 YourSinglePlayerFragment fragment = new YourSinglePlayerFragment(); // 用setArguments把Bundle传给Fragment fragment.setArguments(receivedBundle); // 把Fragment添加到布局容器(替换成你实际的容器ID) getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container, fragment) .commit(); } }
最后,在Fragment中安全接收Bundle
在Fragment里取值时,一定要先判断Bundle是否为空,避免空指针:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = getArguments(); if (bundle != null) { String player1Name = bundle.getString("player1Name"); // 拿到名称后就可以使用了,比如设置到TextView // textViewPlayerName.setText(player1Name); } }
额外注意点
- 确保
textPlayer1的ID和布局文件里的EditText ID完全匹配 - 所有涉及Bundle的地方都要做非空判断,这是避免空指针的关键
内容的提问来源于stack exchange,提问作者kveola92




