gpt4 book ai didi

java - 尽管为其分配了一个值,但仍获取 nullpointerexception

转载 作者:行者123 更新时间:2023-11-29 20:08:59 25 4
gpt4 key购买 nike

我正在创建一个基本的 Android 应用程序。我正在创建一个名为 mathexpresionTVTextView 对象,并分配给我希望它引用的 textview 的 id 值。

TextView mathExpressionTV = (TextView) findViewById(R.id.mathexpressiontextview);

我还有一个按钮,如果用户按下它,它会在 textview 上显示 1。

 Button oneButton = (Button) findViewById(R.id.button1)
oneButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mathExpressionTV.append("0");
}
});

我将在整个类(class)中使用 mathExpressionTV,因此我将其声明为全局变量,而不是在我的 onCreate(); 方法中,而是在 oneButton 在我的 onCreate(); 中声明。

这是错误输出:Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference

最佳答案

您可以将其声明为全局的,但您需要在 onCreate 中将其转换为 TextView。您不能在 Activity 的方法之外使用 findViewById

TextView mathExpressionTV;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourActivity);

mathExpressionTV = (TextView) findViewById(R.id.mathexpressiontextview);

...
}

关于java - 尽管为其分配了一个值,但仍获取 nullpointerexception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35295311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com