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

Android中调用findViewById出现NullPointerException问题求助

解决findViewById引发的NullPointerException问题

嘿,我一眼就揪出问题所在啦!你写的这行代码:

longitude_val=(TextView) longitude_val.findViewById(R.id.longitude_val);

犯了一个超典型的错误——你正在用还没初始化的longitude_val变量去调用findViewById方法!

为什么会触发空指针异常?

当你刚声明TextView longitude_val;时,这个变量的初始值是null。你现在用null.findViewById(...),相当于让一个不存在的对象去执行方法,系统自然会抛出NullPointerException。

正确的写法应该是怎样的?

你得用当前的页面实例(Activity)或者布局根View来调用findViewById:

  • 如果是在Activity中:
    // 务必先调用setContentView加载你的布局文件,否则找不到控件
    setContentView(R.layout.你的布局文件名);
    TextView longitude_val = findViewById(R.id.longitude_val);
    
  • 如果是在Fragment中:
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 用Fragment的根View来查找控件
        TextView longitude_val = view.findViewById(R.id.longitude_val);
    }
    

额外的避坑提醒

  1. 一定要确保在调用findViewById之前,已经通过setContentView(Activity)或onViewCreated(Fragment)加载了对应的布局文件,否则系统找不到控件,findViewById也会返回null。
  2. 检查布局里的android:id="@+id/longitude_val"和代码里的R.id.longitude_val拼写完全一致,哪怕是大小写错误都会导致找不到控件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:53:02