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

Android开发调用TextView.setText出现NullPointerException空指针异常如何解决

问题解决方法

报错根本原因

你的空指针异常由代码执行顺序错误导致:

  • setContentView(R.layout.activity_main) 是Activity加载布局文件的方法,只有执行完该方法后,才能通过findViewById()找到布局里的控件
  • 你当前代码先调用了findViewById(R.id.text1),此时还没有加载布局,找不到对应控件,返回值为null,后续调用setText时就触发了空指针异常。

修复方案

调整onCreate方法里的代码顺序,先加载布局再查找控件,修正后的代码如下:

public class MainActivity extends AppCompatActivity {
    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 第一步:先加载布局
        setContentView(R.layout.activity_main);
        // 第二步:加载完成后再查找控件
        TextView text = (TextView) findViewById(R.id.text1);
        text.setText("Lets try this out");
    }
}

额外优化建议

如果要彻底避免这类空指针问题,可开启Android官方的视图绑定(View Binding)功能,无需手动调用findViewById,也不会出现控件为空的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 14:15:03