为什么当我第二次运行相同的函数时会出现 null 异常?

发布于 2025-01-09 03:13:49 字数 570 浏览 2 评论 0原文

我有一个按钮,我将其称为函数 click 当我第二次单击该按钮时,应用程序崩溃。 这是因为我在 null 对象上调用 setEdit 。 除了第二种变体之外还有其他方法可以解决这个问题吗 下面给出了 if(!=null) ?有没有解释为什么我会收到此 null 异常?

public void click(View view) {

        EditText editText = (EditText)findViewById(R.id.simpleEditText);


    if (editText != null)  { editText.setId(202); }

}

但他的作品很好:

public void click(View view) {

        EditText editText = (EditText)findViewById(R.id.simpleEditText);


    if (editText != null)  { editText.setId(202); }

}

I have a button over which I call the fucntion click
WHen I click the button 2nd time, app crashes.
It is because I call setEdit on null object.
Is there some other way to solve the problem than the second variation
given below with if(!=null) ? Is there an explanation why I'm getting this null exception ?

public void click(View view) {

        EditText editText = (EditText)findViewById(R.id.simpleEditText);


    if (editText != null)  { editText.setId(202); }

}

But his works fine:

public void click(View view) {

        EditText editText = (EditText)findViewById(R.id.simpleEditText);


    if (editText != null)  { editText.setId(202); }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

飘过的浮云 2025-01-16 03:13:49

这是对话中的内容,向他展示了如何获取视图并存储它们。

public class MyActivity extends Activity {

    private TextView text1;

    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.mylayout);
        text1 = findViewById(R.id.text);
    }

    private void someFunc() {
        text1.setText("Hey I used the variable");
    }
}

THis is from the conversation, showing him how to get views and store them.

public class MyActivity extends Activity {

    private TextView text1;

    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.mylayout);
        text1 = findViewById(R.id.text);
    }

    private void someFunc() {
        text1.setText("Hey I used the variable");
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文