Android: OnTextChanged email validation is not working as expected - java

I am using the fololowing code to validate the email input
private boolean validateEmail(String email) {
String emailPattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
Pattern pattern = Pattern.compile(emailPattern);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
I execute this on onTextChanged. The code is below (I am using ButterKnife)
#OnTextChanged(R.id.et_email)
public void checkCorrectEmail() {
if (!validateEmail(mEditTextEmail.getText().toString().trim())) {
isValidated = false;
mEditTextEmail.setError("Please enter email address");
mEditTextEmail.requestFocus();
} else {
isValidated = true;
}
}
The issue is that it is not intelligent enough. For an example, if I type myemail#gmail.com it still show the error message. However if I type myemail#gmail.com then a space and clicked delete the space then everything is fine, error gone.
Formerly this validation was on onClick of a button. What have I done wrong here?

#OnTextChanged(R.id.et_email)
public void checkCorrectEmail () {
if (!validateEmail(mEditTextEmail.getText().toString().trim())) {
isValidated = false;
mEditTextEmail.setError("Please enter email address");
mEditTextEmail.requestFocus();
} else {
isValidated = true;
mEditTextEmail.setError(null);
}
}
100% working

Try this :
#OnTextChanged(R.id.et_email)
public void checkCorrectEmail() {
if (!validateEmail(mEditTextEmail.getText().toString().trim())) {
isValidated = false;
mEditTextEmail.setError("Please enter email address");
mEditTextEmail.requestFocus();
} else {
mEditTextEmail.setError(null)
isValidated = true;
}
}
clear the error on correct input

Use the in-build Email pattern checker method:
#OnTextChanged(R.id.et_email)
public void checkCorrectEmail () {
if (!Patterns.EMAIL_ADDRESS.matcher(mEditTextEmail.getText().toString()).matches()){
isValidated = false;
mEditTextEmail.setError("Please enter a Valid E-Mail Address!");
mEditTextEmail.requestFocus();
}else {
isValidated = true;
mEditTextEmail.setError(null);
}

Related

Trying to enter data in a form in Java before it goes to another form

I have am trying to allow the user to fill in a form in Java after an error message has been displayed indicating that the field is empty. Currently the dialog boxes pop up and then the form goes directly to the next form with out allowing the user to enter anything.
Here is a snippet of the code I am working with:
private void btnEnterActionPerformed(java.awt.event.ActionEvent evt) {
//Confirming that the input fields have values
String un = UserName.getText().toString();
if(un.equals("")) {
JOptionPane.showMessageDialog(null, "Username Required");
}
String pw = Password.getText().toString();
if(pw.equals("")) {
JOptionPane.showMessageDialog(null, "Password Required");
}
//link to HRDBS
HRDBS dbp = new HRDBS();
dbp.setVisible(true);
dbp.pack();
dbp.setLocationRelativeTo(null);
this.dispose();
}
Thank you for your assistance with this matter
it will be a little better if the validation is moved to a separate method and returns on the first error. also you can accumulate errors in one message.
private boolean validateValues() {
String un = UserName.getText().toString();
if(un.equals("")){
JOptionPane.showMessageDialog(null, "Username Required");
return false;
}
String pw = Password.getText().toString();
if(pw.equals("")){
JOptionPane.showMessageDialog(null, "Password Required");
return false;
}
return true;
}
private void btnEnterActionPerformed(java.awt.event.ActionEvent evt) {
//Confirming that the input fields have values
if(validateValues()) {
//link to HRDBS
HRDBS dbp = new HRDBS();
dbp.setVisible(true);
dbp.pack();
dbp.setLocationRelativeTo(null);
this.dispose();
}
}

Programmatically turning on all notifications

I am new to Android development and I can't understand how to properly turn all ble notifications and get all of them.
I've tried to loop through all services
for(BluetoothGattService service : gatt.getServices()){
if( service.getUuid().equals(Step_UUID)) {
BluetoothGattCharacteristic characteristicData = service.getCharacteristic(Step_UUID);
for (BluetoothGattDescriptor descriptor : characteristicData.getDescriptors()) {
descriptor.setValue( BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
gatt.writeDescriptor(descriptor);
}
gatt.setCharacteristicNotification(characteristicData, true);
}
}
but I don't get any notifications back.
Please, help I do not understand what I am doing wrong..
EDIT
Right now I use this method to enable notifications after services are discovered:
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) {
// Setting default write type according to CDT 222486
characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
String serviceUUID = characteristic.getService().getUuid().toString();
String serviceName = GattAttributes.lookupUUID(characteristic.getService().getUuid(), serviceUUID);
String characteristicUUID = characteristic.getUuid().toString();
String characteristicName = GattAttributes.lookupUUID(characteristic.getUuid(), characteristicUUID);
String descriptorUUID = GattAttributes.CLIENT_CHARACTERISTIC_CONFIG;
String descriptorName = GattAttributes.lookupUUID(UUIDDatabase.UUID_CLIENT_CHARACTERISTIC_CONFIG, descriptorUUID);
if (characteristic.getDescriptor(UUID.fromString(GattAttributes.CLIENT_CHARACTERISTIC_CONFIG)) != null) {
if (enabled == true) {
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(GattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
boolean aaa = mBluetoothGatt.writeDescriptor(descriptor);
aaa = mBluetoothGatt.writeDescriptor(descriptor);
aaa = false;
} else {
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(GattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
}
}
boolean aaaa = mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
aaaa = false;
}
The problem is that first characteristic notifies well, but all others I am trying to enable fails on the line
mBluetoothGatt.writeDescriptor(descriptor);
Don't know what to do...
My problem was resolved by overiding onDescriptorWrite method. I made a flag inside, and if it is true I continue to notify all left characteristics.
#Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
String serviceUUID = descriptor.getCharacteristic().getService().getUuid().toString();
String serviceName = GattAttributes.lookupUUID(descriptor.getCharacteristic().getService().getUuid(), serviceUUID);
String characteristicUUID = descriptor.getCharacteristic().getUuid().toString();
String characteristicName = GattAttributes.lookupUUID(descriptor.getCharacteristic().getUuid(), characteristicUUID);
String descriptorUUID = descriptor.getUuid().toString();
String descriptorName = GattAttributes.lookupUUID(descriptor.getUuid(), descriptorUUID);
if (status == BluetoothGatt.GATT_SUCCESS) {
written = true;
numberLeft--;
} else {
written = true;
numberLeft--;
}
}

Email validation only when field is not blank in Android

Validate email format only if EditText is not blank in Android. And if the field is blank validation should not be check. I did not find any solution in this scenario which is useful for me.
Try this code
final EditText emailEditTxt= (EditText)findViewById(R.id.text);
String emailStr = emailEditTxt.getText().toString().trim();
if(emailStr!=null)
if(emailStr.length()>=1){
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (emailStr .matches(emailPattern))
{
Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),"Invalid email address", Toast.LENGTH_SHORT).show();
}
}
Try this..
boolean flag;
String pass = editText.getText().toString().trim();
if(!pass.equals("")) {
flag = isEmailValid(pass);
}
public static boolean isEmailValid(CharSequence email) {
return Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
and use the flag value for further use
Use this method for check email pattern is valid or not
public static boolean isEmailValid(CharSequence email) {
return Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
validateEmail
private boolean validateEmail() {
if (!edemail.getText().toString().trim().isEmpty()&&!ValidationMethod.emailValidation(edemail.getText().toString()))
{
input_layout_email.setError("Invalid Email"); // Your textInput Layout or other set your error on edittext email
requestFocus(edemail);
return false;
}
else {
input_layout_email.setErrorEnabled(false);
}
return true;
}
// if you need requestfocus other wise remove
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
ValidationMethod.java // put in your project
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ValidationMethod {
static Matcher m;
static String emailExpression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,20}$";
static Pattern emailPattern = Pattern.compile(emailExpression, Pattern.CASE_INSENSITIVE);
static String passwordExpression ="((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\\W).{8,20})";
static Pattern passwordPattern=Pattern.compile(passwordExpression);
public static boolean emailValidation(String s)
{
if( s == null)
{
return false;
}
else
{
m = emailPattern.matcher(s);
return m.matches();
}
}
public static boolean passwordValidation(String s)
{
if( s == null)
{
return false;
}
else
{
m = passwordPattern.matcher(s);
return m.matches();
}
}
public static boolean emailValidation2(String s)
{
m = emailPattern.matcher(s);
return m.matches();
}
}
try This
<form>
<lable for="userEmail">Email : </label>
<input type="email" id="userEmail" placeholder="johndoe#example.com" required="required">
<form>
Lets say you have declared EditText like this.
EditText emailField;
then in your method
emailField = (EditText)view.getViewById(R.id.NAME_OF_FIELD_IN_XML);
if(!TextUtils.isBlank(emailField.getText().toString())){
//validate your email address
}
Use below link for email validation code.
http://stackoverflow.com/questions/12947620/email-address-validation-in-android-on-edittext
You can try this for validation.
public boolean Email_validation(String CorpId)
{
String regExpn =
"^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))#"
+"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+"[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
+"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+"[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+"([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";
CharSequence inputStr = CorpId;
Pattern pattern = Pattern.compile(regExpn, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if(matcher.matches())
return true;
else
return false;
}

how to highlight a input field in an android application in java

i am working on an android application registration page(in java language) where it contains 13 fields. i have done validation to all the fields and its working fine with toast messages. but my requirement is if any field raises a toast message then that field should be highlighted. here is my sample code
if (driverName.length() <= 0) {
Toast.makeText(ApplicationActivity.this, "Enter first name", Toast.LENGTH_LONG).show();
} else if (firname) {
Toast.makeText(ApplicationActivity.this, "please enter the first name correctly", Toast.LENGTH_LONG).show();
} else if (driverName_last.length() <= 0) {
Toast.makeText(ApplicationActivity.this, "Enter last name", Toast.LENGTH_LONG).show();
} else if (secname) {
Toast.makeText(ApplicationActivity.this, "please enter last name correctly", Toast.LENGTH_LONG).show();
} else if (fatherName.length() <= 0) {
Toast.makeText(ApplicationActivity.this, "Enter father name", Toast.LENGTH_LONG).show();
} else if (fathername) {
Toast.makeText(ApplicationActivity.this, "please enter father name correctly", Toast.LENGTH_LONG).show();
}
thanks in advance
You can use setError() method as follows instead of using Toast.
input.setError("Your particular error");
where, input is your EditText.
It will set the error to particular EditText when your if condition will be wrong or according to your given condition with the particular error message.
Its the better way than displaying Toast.
EDITED WITH CODE:
if (!Common.isValidLength(fName)) {
medFirstName.setError("Invalid First Name");
}
if (!Common.isValidLength(lName)) {
medLastName.setError("Invalid Last Name");
}
if (!Common.isValidEmail(email)) {
medEmailId.setError("Invalid Email");
}
if (!Common.isValidPassword(pass)) {
medPassword.setError("Invalid Password");
}
if (!Common.isValidPassword(confirmPassword)) {
medConfirmPassword.setError("Invalid Confirm Password");
}
if (!Common.isValidMatchPassword(pass, confirmPassword)) {
medConfirmPassword.setError("Password does not match");
}
For that create one Common class and put below methods in it :
/*
* A Common function to check internet connection.
* */
public static boolean isOnline(Context c) {
try {
ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/*
* A common function to check length for input.
* */
public static boolean isValidLength(String fName) {
if (fName.trim().length() > 0) {
return true;
}
return false;
}
/*
* A common function to validate Email id.
* */
public static boolean isValidEmail(String email) {
String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
// validating password with retype password
public static boolean isValidPassword(String password) {
if (password != null) {
return true;
}
return false;
}
// validating of confirm password
public static boolean isValidMatchPassword(String pass, String confirmPassword) {
if (pass.equals(confirmPassword)) {
return true;
}
return false;
}
To hightlight field you have to set foucs for e.g.
firname.requestFocus();
Note: change firname with your edittext name.
requestFocus() method will return focus to view on which it is called.
for example
else if (firname) {
Toast.makeText(ApplicationActivity.this, "please enter the first name correctly", Toast.LENGTH_LONG).show();
firname.requestFoucs(); ****// here firname is edittext****
}

Using Command pattern for undo and redo in ArrayLists

So I have a program where you can log in and add/remove friends to and from the friends arraylist. Also I can like a certain thing and that thing will be stored into the likes arraylist. I'm asked to make undo and redo options for whichever action I do.
So I want to add apple as a friend. After that when I select the undo option, I can undo that action so apple wouldn't be my friend. How I can approach this with a Command Pattern when the input is whatever name or word I inputted to store into the friends arraylist?
I did some research and found that using a command pattern could be my best bet since this has to be done under the Facebook Class I already have. I'm assuming I'll have to use two different stacks, but I'm getting a bit lost in the topic.
I decided to add parts of what I have so that I can get a bit more help on what I need to do and what my program does.
In the driver program
Facebook facebook1 = new Facebook();
if (userInput == 6)
{
System.out.println("Login");
String operand1 = getOperand("What is the Username? ");
String operand2 = getOperand("What is the Password? ");
System.out.println("Enter a friend to be added. ");
String operand3 = getOperand("What is the Username? ");
facebook1.friend(operand3);
}
if (userInput == 7)
{
System.out.println("Login");
String operand1 = getOperand("What is the Username? ");
String operand2 = getOperand("What is the Password? ");
System.out.println("Enter a friend to be removed. ");
String operand3 = getOperand("What is the Username? ");
facebook1.defriend(operand3);
}
if (userInput == 12)
{
System.out.println("Login");
String operand1 = getOperand("What is the Password? ");
facebook1.undo();
}
if (userInput == 13)
{
System.out.println("Login");
String operand1 = getOperand("What is the Password? ");
facebook1.redo();
}
In the Facebook Class
ArrayList<FacebookUser> recommendedFriends = new ArrayList<FacebookUser>();
void friend(String newFriend)
{
boolean positiveChecker = false;
for (int i = 0; i < recommendedFriends.size(); i++)
{
if (recommendedFriends.get(i).toString().equalsIgnoreCase(newFriend))
{
System.out.println("Error: This friend already exists.");
positiveChecker = true;
}
}
if (positiveChecker == false)
{
FacebookUser friend = new FacebookUser(newFriend, newFriend );
recommendedFriends.add(friend);
System.out.println(friend + " is now your friend.");
}
positiveChecker = false;
}
void defriend(String formerFriend)
{
boolean positiveChecker = false;
for (int i = 0; i < recommendedFriends.size(); i++)
{
if (recommendedFriends.get(i).toString().equalsIgnoreCase(formerFriend))
{
recommendedFriends.remove(i);
System.out.println(formerFriend + " has been removed from your friends list.");
positiveChecker = true;
}
if (recommendedFriends.size() == (i + 1) && recommendedFriends.get(i).toString() != formerFriend
&& positiveChecker == false)
{
System.out.println("Error: There is no friend with this username.");
}
}
positiveChecker = false;
}
public interface Command
{
public void undo();
public void redo();
}
When you undo 2 things then do a completely new action, you need to "forget" the "redo history" and replace it with the new command, right?
For example...
Add Friend Jim
Add Friend Bill
Add Friend Jill
Remove Jim
Undo
Undo
State should be "Jim" and "Bill".
So you only really need one list and a pointer to the current "command", for example...
// Note: NOT thread safe!
public class CommandStack {
private List<Command> commands = Collections.emptyList();
private int nextPointer = 0;
public void doCommand(Command command) {
List<Command> newList = new ArrayList<>(nextPointer + 1)
for(int k = 0; k < nextPointer; k++) {
newList.add(commands.get(k));
}
newList.add(command);
commands = newList;
nextPointer++;
// Do the command here, or return it to whatever called this to be done, or maybe it has already been done by now or something
// (I can only guess on what your code currently looks like...)
command.execute();
}
public boolean canUndo() {
return nextPointer > 0;
}
public void undo() {
if(canUndo()) {
nextPointer--;
Command commandToUndo = commands.get(nextPointer);
// Undo the command, or return it to whatever called this to be undone, or something
command.undo();
} else {
throw new IllegalStateExcpetion("Cannot undo");
}
}
public boolean canRedo() {
return nextPointer < commands.size();
}
public void redo() {
if(canRedo()) {
commandToDo = commands.get(nextPointer);
nextPointer++;
// Do the command, or return it to whatever called this to be re-done, or something
commandToDo.execute();
} else {
throw new IllegalStateException("Cannot redo");
}
}
}
If I had...
interface Command { /* execute / undo etc */ }
public class AddFriendCommand implements Command {
private String friendName;
// ... other fields, constructor / getters etc ...
public void execute() {
// Actually do it...
System.out.println("Added friend " + name);
}
public void undo() {
// Undo it...
System.out.println("Removed friend " + name);
}
}
public class RemoveFriendCommand implements Command {
private String friendName;
// ... other fields, constructor / getters etc ...
public void execute() {
// Actually do it, maybe throw exception if friend does not exist?
// (that would have to be a runtime exception unless you want the interface's method to throw stuff);
System.out.println("Removed friend " + name);
}
public void undo() {
// Undo it...
System.out.println("Added friend " + name);
}
}
You could repeat the sequence above using...
CommandStack stack = new CommandStack();
stack.doCommand(new AddFriendCommand("Jim"));
stack.doCommand(new AddFriendCommand("Bill"));
stack.doCommand(new AddFriendCommand("Jill"));
stack.doCommand(new RemoveFreindCommand("Jim"));
stack.undo();
stack.undo();
If you now did a new command (via doCommand) it would forget that you ever added "Jill" or removed "Jim", but instead would now remember the new command and the rest of the command history that was not undone.
Hope this helps.
You are misunderstanding how the command pattern works. You want to have a separate List of your Commands, where each instance of Command represents an action.
So you would want to have something like:
List<Command> actionStack;
and then have stuff like
public class AddCommand implements Command {
private final void List<FacebookUser> userList;
private final void FacebookUser newUser;
public AddCommand(List<FacebookUser> userList, FacebookUser newUser) {
this.userList = userList;
this.newUser = newUser;
}
#Override
public void undo() {
userList.remove(newUser);
}
#Override
public void redo() {
userList.add(newUser);
}
}

Categories