gpt4 book ai didi

java - NullPointerException 发生在 onClick 方法上

转载 作者:行者123 更新时间:2023-12-01 07:55:12 25 4
gpt4 key购买 nike

我创建了一个验证电子邮件格式的类。

public class EmailValidator {
private Pattern pattern;
private Matcher matcher;

// regular expression for email validation
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

public EmailValidator() {
pattern = Pattern.compile(EMAIL_PATTERN);
}

public boolean validate(final String email) {
matcher = pattern.matcher(email);
return matcher.matches();
}
}

通过使用上面的类,我想实现一个代码,该代码实际执行验证并在电子邮件不是有效格式时发送 toast。所以我创建了另一个代码,如下所示。

RegisterActivity.java

(1) 变量

EmailValidator validator;
EditText etEmail;

(2)onClick方法

String email = etEmail.getText().toString();
**if(validator.validate(email) == false)** {
Toast.makeText(getApplicationContext(), "Wrong email format.", Toast.LENGTH_LONG).show();

到目前为止,代码似乎没有问题,但是当我运行它时,它在上面的部分抛出了 NullPointerException 。我错过了什么吗?

如果您需要进一步了解代码,请告诉我,以便我尽快更新。谢谢!

更新:这是 logcat。

07-07 20:05:30.761      342-342/com.marshall.gruppo E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.marshall.gruppo, PID: 342
java.lang.NullPointerException
at com.marshall.gruppo.ui.RegisterActivity$1.onClick(RegisterActivity.java:101)
at android.view.View.performClick(View.java:4633)
at android.view.View$PerformClick.run(View.java:19270)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5602)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)

最佳答案

您必须像这样创建 EmailValidator 类的对象

EmailValidator validator = new EmailValidator();
if(validator.validate(email) == false) {
//do your operation here
}

关于java - NullPointerException 发生在 onClick 方法上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31276371/

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