我创建了一个类来验证电子邮件格式。
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();
}
}
通过使用上面的类,我想实现一个代码,该代码实际上执行验证,如果电子邮件不是有效格式,则发送祝酒词。因此,我创建了另一个代码,如下所示。
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异常。我想念什么吗?
如果您需要进一步了解代码,请告诉我,以便我尽快进行更新。谢谢!
更新:这是日志。
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
}