You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Android调用Bundle.getString时报空对象引用的崩溃问题

错误根因
  • 你在入门引导页仅将账号名称参数传递给了HomeMenu页面,从HomeMenu点击打开Profile页面时,没有将该参数继续传递,因此Profile页面拿到的Intent没有附带任何Bundle数据,调用bn.getString()时bn本身为null,直接触发空指针异常。
修复方案

这里提供两种常用实现方案,按需选择即可:

方案1:使用SharedPreferences全局存储(更推荐,适合账号名这类全局通用的用户信息)

步骤1:修改入门引导页存储逻辑

continueBtn = findViewById(R.id.continueBtn);
continueBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        String Data = accountNameSignup.getText().toString();
        // 存入全局共享配置
        SharedPreferences sp = getSharedPreferences("app_user_info", MODE_PRIVATE);
        sp.edit().putString("account_name", Data).apply();
        
        Intent intent = new Intent(GettingStarted.this, HomeMenu.class);
        startActivity(intent);
        finish();
    }
});

步骤2:修改Profile页面读取逻辑

accountName = findViewById(R.id.accountName);
SharedPreferences sp = getSharedPreferences("app_user_info", MODE_PRIVATE);
// 第二个参数为读取失败时的默认值
String updateName = sp.getString("account_name", "未设置昵称");
accountName.setText(updateName);

方案2:从HomeMenu跳转时携带参数

步骤1:修改HomeMenu跳转Profile的逻辑

在HomeMenu页面中,点击跳转到Profile的代码处增加参数传递:

// 先读取入门引导页传给HomeMenu的参数
String accountName = getIntent().getStringExtra("abc");
Intent profileIntent = new Intent(HomeMenu.this, Profile.class);
profileIntent.putExtra("abc", accountName);
startActivity(profileIntent);

步骤2:给Profile页面增加空判断(最佳实践,避免异常)

即使参数传递正常,也建议增加空判断逻辑避免异常崩溃:

accountName = findViewById(R.id.accountName);
Bundle bn = getIntent().getExtras();
if(bn != null){
    String updateName = bn.getString("abc");
    accountName.setText(updateName != null ? updateName : "未设置昵称");
}else{
    accountName.setText("未设置昵称");
}

内容的提问来源于stack exchange,提问作者newbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 02:36:08