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

Android开发调用findViewById出现NullPointerException空指针异常求助

错误原因

空指针异常的根源是你在Activity类的成员初始化阶段就调用了findViewById()方法,同时尝试读取控件文本值。此时Activity还未执行onCreate()生命周期方法,setContentView()尚未加载布局,Activity的上下文Context还未完成初始化,调用依赖Context的方法就会触发该报错。

修复方案

先仅声明控件和数值变量,所有控件查找、初始值读取的逻辑都放到onCreate()的setContentView()之后执行,修改后代码如下:

package com.kuldeep.justjava;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    // 仅声明变量,不做初始化
    TextView textView2;
    TextView textView4;
    int quantity;
    String s;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 布局加载完成后再查找控件、读取初始值
        textView2 = findViewById(R.id.textView2);
        textView4 = findViewById(R.id.textView4);
        quantity = Integer.parseInt(textView2.getText().toString());
    }

    public void subtraction(View view){
        if(quantity != 0){
            quantity--;
        }
        s = Integer.toString(quantity);
        textView2.setText(s);
    }

    public void plus(View view){
        quantity++;
        s = Integer.toString(quantity);
        textView2.setText(s);
    }

    public void order(View view){
        int price = 5 * quantity;
        String p = "$ " + price;
        textView4.setText(p);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:45:08