I have an activity that has two EditText boxes, one email and one plain text. I want to check that the email box is not empty and also that is matches an email pattern before allowing the user to move on. The pattern matcher part works, but the empty string part doesn't.
I validate as the user enters data, and then set the two buttons to the be clickable or not according to whether the email is correct. However, if the box is empty, it allows the user to press the button when it shouldn't. When there is text in the box, it does the correct thing of only letting the user press the button when the email pattern has been matched.
My after text changed method:
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
String enteredEmail = email.getText().toString();
if (validateEmail(enteredEmail) == true) {
image1.setImageResource(R.drawable.greentick);
play.setClickable(true);
play.setFocusable(true);
existingUser.setClickable(true);
existingUser.setFocusable(true);
}
else {
System.out.println("Invalid");
image1.setImageResource(R.drawable.redcross);
play.setClickable(false);
play.setFocusable(false);
existingUser.setClickable(false);
existingUser.setFocusable(false);
}
}
And my validateEmail() method:
public boolean validateEmail(String email) {
boolean validated = false;
if (android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches() && (! email.equals("")) ) {
validated = true;
}
else {
validated = false;
}
return validated;
}
TextChanged won't fire if the user hasn't entered anything, as the text hasn't changed... You should disable the button by default.
Have you tried debugging, as this should have shown you the event isn't firing.
this is how i validate email fields (regular expressions):
private Boolean validateEmail(String email)
{
return email.matches("^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*#[a-zA-Z](-?[a-zA-Z0-9])*(\\.[a-zA-Z](-?[a-zA-Z0-9])*)+$");
}
FYI: i dont remember offhand, you may need org.apache.commons.lang3.stringutils
Related
I have a login form which contains two edit texts, one to enter an emailId and another to enter a password. I have written a simple method to validate that these fields are not empty. This is my method
public boolean validate() {
if(edtEmail.getText().toString().trim().equalsIgnoreCase("")){
showErrorMessage(true);
return false;
}
if(edtPassword.getText().toString().trim().equalsIgnoreCase("")){
showErrorMessage(false);
return false;
}
return true;
}
I have written a unit test for this method
#Test
public void check_validate() {
EditText edtEmail = loginActivity.findViewById(R.id.edtEmail);
EditText edtPassword=loginActivity.findViewById(R.id.edtPassword);
assertTrue(loginActivity.validate());
}
I am getting the error as java.lang.AssertionError. All i want to check is whether the function is working correctly.
this is the question Shows the log-in form; the app must generate a message box notifying the user “Please Complete the required field” when the user leave the two text boxes blank ,while clicking the login button; wherein a generated message box pop and notify the user that “Wrong password!” when the user input the correct username and wrong password it will automatically clear the password textbox; wherein the app must generate a message box that notify the user that “Wrong Username!” if the user input the wrong username and correct password it will and automatically clear the username textbox; wherein the app must generate a messages box that notify the user that “Wrong Username and password!” if the user input both wrong username and wrong password it will automatically clear the password and username textboxes and set the text focus to the username textbox; wherein ;the app must notify the user “WELCOME” if when the user input the correct username and password it will automatically close the login activity and open the next activity.
Note: the Username and password must be both “admin”.
Button login;
EditText user, pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
user = (EditText)findViewById(R.id.editText1 );
pass = (EditText)findViewById(R.id.editText2 );
login = (Button)findViewById(R.id.button1 );
login.setOnClickListener((OnClickListener) this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(user.equals("admin") && (pass.equals("admin"))){
System.out.println("Welcome!");
Intent intent = new Intent(this, Home.class);
startActivity(intent);
}else if (user.equals(null) && (pass.equals("admin"))) {
System.out.println ("Please Complete Required Field!");
}else if (user.equals("admin") && (pass.equals(null))) {
System.out.println ("Please Complete Required Field!");
}else {
System.out.println ("Wrong Username! or Wrong Password!");
}
}
}
To detect whether the editText is empty or not:
Change (user.equals(null)) to user.getText().toString().trim().length() == 0
and pass.equals(null) to pass.getText().toString().trim().length() == 0
In your button implementation, write like login.setOnClickListener(this); and make sure your Activity/Fragment implement OnClickListener like #pcg26 said.
Make sure you have implemented onClickListener.
In your onClick method, You must use a switch or if statement to make sure that the button is clicked.
Something like this:
public void onClick(View v) {
if(v.getId() == R.id.yourButtonID){
// do here
}
}
Is the activity implementing onclicklistener?
Simple a comment.. You can use Log.e("MyActivity"," the error"); instead System.out.println ^^
I have a DialogFragment that contains AutoCompleteTextView, and Cancel and OK buttons.
The AutoCompleteTextView is giving suggestions of usernames that I'm getting from server.
What I want to do is to restrict the user to be able to enter only existing usernames.
I know I can do check if that username exists when the user clicks OK, but is there some other way, let's say not allow the user to enter character if there doesn't exist such username. I don't know how to do this because on each entered character I'm getting only up to 5 suggestions. The server is implemented that way.
Any suggestions are welcomed.
Thank you
I couldn't find more suitable solution then this:
I added this focus change listener
actName.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
ArrayList<String> results =
((UsersAutoCompleteAdapter) actName.getAdapter()).getAllItems();
if (results.size() == 0 ||
results.indexOf(actName.getText().toString()) == -1) {
actName.setError("Invalid username.");
};
}
}
});
Where the method getAllItems() returns the ArrayList containing the suggestions.
So when I enter some username, and then move to another field this listener is triggered and it checks if the suggestions list is not empty and if the entered username is in that list. If the condition is not satisfied, an error is shown.
Also I have the same check on OK button click:
private boolean checkErrors() {
ArrayList<String> usernameResults =
((UsersAutoCompleteAdapter) actName.getAdapter()).getAllItems();
if (actName.getText().toString().isEmpty()) {
actName.setError("Please enter a username.");
return true;
} else if (usernameResults.size() == 0 || usernameResults.indexOf(actName.getText().toString()) == -1) {
actName.setError("Invalid username.");
return true;
}
return false;
}
So if the AutoComplete view is still focused, the error check is done again.
I have created an activity that refresh quotes when the user clicks a button. Within the same activity there is a check box which the users can click if they like the quote.
Everything works perfectly apart from the check box. When the user clicks they like the quote, I want that check box checked. This only happens when the user moves away from the activity and returns at a later stage.
However when the user stays within the activity and returns to the quote, the old state is shown instead of the users preference.
The check box is configured from the values even in the database, if the value is 1, the check box should be ticked, if not, check box should be clear.
The code is shown below:
When the user clicks the next button, the following code is executed:
Button nextGenerateButton = (Button) findViewById(R.id.btn_next_quotes);
nextGenerateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String nextQuote = myDbHelper.getnextQuote();
setQuoteDisplay(nextQuote);
btn_favorite.setChecked(myDbHelper.getFavouriteCheckBoxValue());
}
});
The button retrieves the next quote and the getFavouriteCheckBoxValue() confirms whether the favourite column is marked in the database and either returns a true of false which sets the check box value.
public boolean getFavouriteCheckBoxValue()
{
int laballedFavourite = cursor.getInt(0);
if(laballedFavourite == 0)
{
return false;
}
else
{
return true;
}
}
if the user likes the quote, the code executes the addFavourite() which updates the table where the favourite column will be modified on one.
btn_favorite.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked == true)
{
myDbHelper.addFavourite();
}
if(isChecked == false)
{
myDbHelper.removeFavourite();
}
}
});
public void addFavourite()
{
ContentValues vals = new ContentValues();
vals.put("favouriteQuote", 1);
db.update(TABLE_NAME, vals, "columnId = " + cursor.getInt(1), null);
}
Again this only works perfectly when I resume the quote activity and not when I am currently live in the quote activity.
Hope this makes sense.
Any help would be greatly appreciated.
You need to refresh your checkbox to see the changement because you made a changement in you db but not on the UI. You need to observe the db and refresh the checkbox after a modification.
Refreshing cursor solved the problem.
Please how can i apply this code to my android application. I am making an application that gives access to the User by entering the correct password.
I seem to be getting an error with the Console
public static void main (String args[]) throws IOException {
Console c=System.console();
String login = c.readLine("Enter your login: ");
char [] oldPassword = c.readPassword("Enter your old password: ");
if (verify(login, oldPassword)) {
boolean noMatch;
do {
char [] newPassword1 =
c.readPassword("Enter your new password: ");
char [] newPassword2 =
c.readPassword("Enter new password again: ");
noMatch = ! Arrays.equals(newPassword1, newPassword2);
if (noMatch) {
c.format("Passwords don't match. Try again.%n");
} else {
change(login, newPassword1);
c.format("Password for %s changed.%n", login);
}
Arrays.fill(newPassword1, ' ');
Arrays.fill(newPassword2, ' ');
} while (noMatch);
}
Arrays.fill(oldPassword, ' ');
}
//Dummy change method.
static boolean verify(String login, char[] password) {
// this method always returns true in this example.
// modify this method to verify password according to your rules.
return true;
}
//Dummy change method.
static void change(String login, char[] password) {
// modify this method to change password according to your rules.
}
}
Yes you can re-use your verify and change apis for android but you have discard whatever in the main method.
On Android, you will be creating an Activity having three EditText (for hide user text use android:inputType="textPassword"), one for each.
Old Password
New Password
New Password Again
Then you ll have one button call it Change Password. To this Change Password button you can add onClickListenr. When user presses this Change Password button, you will fetch the text values from EditText and then user your verify and change apis to do the actual work.
You can optionally choose a Cancel button too.
Below is how screen will look:
Snippet of handling the Change button:
// Declared in your Activity class.
EditText editTextOldPass;
EditText editTextNewPass;
EditText editTextNewPassAgain;
String login = "";
public void onCreate(Bundle savedInstanceState) {
editTextOldPass = (EditText) findViewById(R.id.editTextOldPass);
editTextNewPass = (EditText) findViewById(R.id.editTextNewPass);
editTextNewPassAgain = (EditText) findViewById(R.id.editTextNewPassAgain);
Button buttonChange = (Button) findViewById(R.id.buttonChange);
buttonChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editTextNewPass.getText().equals(editTextNewPassAgain)) {
if (verify(login, editTextOldPass.getText().toString().toCharArray()))
change(login, editTextNewPass.getText().toString().toCharArray());
} else {
Log.i("PasswordActivity", "Passwords don't match. Try again.");
}
}
});
}