Validating Multiple edittext and showing edittext.setError("String"); - java

I am trying to validate some edittext. I Made 7 edittexts. Phone number ,First name , Last name , Pickup Address, Postal Code, Pickup time, Number of products. As u can see i made 7 edittexts and I want to validate them so that when i press the button to go to next page it does all the database posting and getting on that button. I've already made a method (public void addInfo) and now i am adding the validations on the View.OnClick implemented methods. Here is my Code i wrote for validations.
public void onClick(View v) {
if (v == nextbuttonjava) {
if(phnumberjava.getText().toString().length() < 10)
{
phnumberjava.setError("Invalid Phone Number");
}
if(firstnamejava.getText().toString().length() == 0)
{
firstnamejava.setError("Whats your first name?");
}
if(lastnamejava.getText().toString().length() == 0)
{
lastnamejava.setError("Whats your last name?");
}
if(pickupaddressjava.getText().toString().length() == 0)
{
pickupaddressjava.setError("Enter your address");
}
if(postalcodejava.getText().toString().length() < 6)
{
postalcodejava.setError("Invalid postal code");
}
if(pickuptimejava.getText().toString().length() == 0)
{
pickuptimejava.setError("Enter pickuptime");
}
if(numberstuffjava.getText().toString().length() == 0) {
numberstuffjava.setError("Enter number of clothes");
}
else
{
addInfo();
Intent nextpageintent = new Intent(Afterfullscreen.this, Extrainformation.class);
startActivity(nextpageintent);
}
}
}
I Want that every If statement should be true to make the else work so the intent works and i go to the other activity. But its not the scene here. Only the phone number works good(If i enter the phone number below 10 digits it shows the error and it doesn't run else part). My main concern is that I Have 7 edittexts and Even if one If statement goes true then the else shouldn't be running and i shouldn't go to next intent with posting incomplete data on my database.I Want that even if any of the edittexts if statement goes wrong i should get an error (eg, numberstuffjava.setError("Input Something");.
How to resolve the issue?

Try something like this:
public void onClick(View v) {
if (v == nextbuttonjava) {
boolean error = false;
if(phnumberjava.getText().toString().length() < 10)
{
error = true;
phnumberjava.setError("Invalid Phone Number");
}
if(firstnamejava.getText().toString().isEmpty())
{
error = true;
firstnamejava.setError("Whats your first name?");
}
if(lastnamejava.getText().toString().isEmpty())
{
error = true;
lastnamejava.setError("Whats your last name?");
}
if(pickupaddressjava.getText().toString().isEmpty())
{
error = true;
pickupaddressjava.setError("Enter your address");
}
if(postalcodejava.getText().toString().length() < 6)
{
error = true;
postalcodejava.setError("Invalid postal code");
}
if(pickuptimejava.getText().toString().isEmpty())
{
error = true;
pickuptimejava.setError("Enter pickuptime");
}
if(numberstuffjava.getText().toString().isEmpty())
{
error = true;
numberstuffjava.setError("Enter number of clothes");
}
if(!error)
{
addInfo();
Intent nextpageintent = new Intent(Afterfullscreen.this, Extrainformation.class);
startActivity(nextpageintent);
} else {
//manage error case here
}
}
}
another option could be this:
if (v == nextbuttonjava) {
if(phnumberjava.getText().toString().length() < 10)
{
phnumberjava.setError("Invalid Phone Number");
}
else if(firstnamejava.getText().toString().isEmpty())
{
firstnamejava.setError("Whats your first name?");
}
else if(lastnamejava.getText().toString().isEmpty())
{
lastnamejava.setError("Whats your last name?");
}
else if(pickupaddressjava.getText().toString().isEmpty())
{
pickupaddressjava.setError("Enter your address");
}
else if(postalcodejava.getText().toString().length() < 6)
{
postalcodejava.setError("Invalid postal code");
}
else if(pickuptimejava.getText().toString().isEmpty())
{
pickuptimejava.setError("Enter pickuptime");
}
else if(numberstuffjava.getText().toString().isEmpty())
{
numberstuffjava.setError("Enter number of clothes");
}
else
{
addInfo();
Intent nextpageintent = new Intent(Afterfullscreen.this, Extrainformation.class);
startActivity(nextpageintent);
}
else
{
//manage error case here
}
}
In this way you check any case with the else if. I prefer the first solution because it's more "flexible".
Hope this helps!

if(phnumberjava.getText().toString().length() < 10)
{
phnumberjava.setError("Invalid Phone Number");
return "Error message";
}
else {
return null;
}
return like this in each and every if condition. If the return statement is null, then all if conditions are true. else show the error message returned

Among other things, you can try the following logic. Here, you can be assured that all the error messages will be shown:
if (v == nextbuttonjava) {
boolean validated = true;
if(phnumberjava.getText().toString().length() < 10)
{
phnumberjava.setError("Invalid Phone Number");
validated = false;
}
if(firstnamejava.getText().toString().length() == 0)
{
firstnamejava.setError("Whats your first name?");
validated = false;
}
if(lastnamejava.getText().toString().length() == 0)
{
lastnamejava.setError("Whats your last name?");
validated = false;
}
if(pickupaddressjava.getText().toString().length() == 0)
{
pickupaddressjava.setError("Enter your address");
validated = false;
}
if(postalcodejava.getText().toString().length() < 6)
{
postalcodejava.setError("Invalid postal code");
validated = false;
}
if(pickuptimejava.getText().toString().length() == 0)
{
pickuptimejava.setError("Enter pickuptime");
validated = false;
}
if(numberstuffjava.getText().toString().length() == 0) {
numberstuffjava.setError("Enter number of clothes");
validated = false;
}
// fire in the hole !
if (validated)
{
addInfo();
Intent nextpageintent = new Intent(Afterfullscreen.this, Extrainformation.class);
startActivity(nextpageintent);
}
}

The else condition it's only attached to the numberstuffjava if condition, in this scenario the else condition will be called always when this if condition is false.
Try changing the previous if conditions with else if.

You just create a method which return true only if all your needs are satisfied. if the method return true, then only go to next activity. I will give an example here.
public boolean isValid(){
if(phnumberjava.getText().toString().length() < 10)
{
phnumberjava.setError("Invalid Phone Number");
return false;
}
if(firstnamejava.getText().toString().length() == 0)
{
firstnamejava.setError("Whats your first name?");
return false;
}
return true;
}
Then do things like below.
if(isValid()){
addInfo();
Intent nextpageintent = new Intent(Afterfullscreen.this, Extrainformation.class);
startActivity(nextpageintent);
}

just add else if for checking all validation
if (v == nextbuttonjava) {
if (edittext1.getText().toString().length() < 5) {
edittext1.setError("error");
} else if (edittext2.getText().toString().length() == 0) {
edittext2.setError("error");
} else {
// your intent here
}
}
add else if for every of your edittext .

Try out below method to check an empty value of edittext.
public static boolean m_isError = false;
/**
* This is method to check edit text empty or not.
*
* #param p_editText
* - edittext
* #param p_nullMsg
* -display message if edittext null
*/
public static void validateForEmptyValue(EditText p_editText,
String p_nullMsg) {
if (p_editText != null && p_nullMsg != null) {
// use trim() while checking for blank values
if (TextUtils.isEmpty(p_editText.getText().toString().trim())) {
m_isError = true;
p_editText.setError(p_nullMsg);
}
}
}
Use the above method as below for each of your edittext:
CustomValidator.m_isError = false;
CustomValidator.validateForEmptyValue(metfirstname, "enter firstname", metfirstname);
CustomValidator.validateForEmptyValue(metlastname, "enter lastname", metlastname);
if (!CustomValidator.m_isError) {
//Define your logic once all the validations are done.
addInfo();
Intent nextpageintent = new Intent(Afterfullscreen.this, Extrainformation.class);
startActivity(nextpageintent);
}

Related

Why does my program say the ArrayList element exists when I try to add it even though it's new?

I am adding elements to an ArrayList and I have it designed to show an error whenever the user tries to add a preexisting element (same for when it tries to remove a nonexistent element). From what it is showing, it adds the new element but still says that the element matches one that is already in the ArrayList. What have I been overlooking? The ArrayList is created and manipulated in the FacebookUser.java class. Thanks (and I apologize in advance if it's a silly mistake).
DriverClass.java
public class DriverClass {
public static void main(String[] args) {
FacebookUser fu0 = new FacebookUser("Samuel", "password1");
FacebookUser fu1 = new FacebookUser("Michael", "password2");
FacebookUser fu2 = new FacebookUser("Amy", "password3");
FacebookUser fu3 = new FacebookUser("Eugene", "password4");
fu0.setPasswordHint("p1");
fu3.setPasswordHint("p4");
fu0.friend(fu1);
fu0.friend(fu2);
fu0.friend(fu3);
fu0.friend(fu3);
System.out.println(fu0.getFriends());
fu0.defriend(fu1);
fu0.defriend(fu1);
System.out.println(fu0.getFriends());
fu0.getPasswordHelp();
fu3.getPasswordHelp();
}
}
FacebookUser.java
import java.util.ArrayList;
public class FacebookUser extends UserAccount {
private String passwordHint;
private ArrayList<FacebookUser> friends = new ArrayList<FacebookUser>();
public FacebookUser(String username, String password) {
super(username, password);
friends = new ArrayList<FacebookUser>();
}
#Override
public void getPasswordHelp() {
System.out.println("Password Hint: " + passwordHint);
}
void setPasswordHint(String hint) {
passwordHint = hint;
}
void friend(FacebookUser newFriend) {
System.out.println(friends.size());
if (friends.size() == 0) {
friends.add(newFriend);
} else {
for (int i = 0; i < friends.size(); i++) {
if (friends.get(i).equals(newFriend)) {
System.out.println("That person is already in your friends list.");
break;
} else if (!friends.get(i).equals(newFriend) && i == friends.size() - 1) {
friends.add(newFriend);
}
}
}
}
void defriend(FacebookUser formerFriend) {
if (friends.size() == 0) {
System.out.println("That person is not in your friends list.");
} else {
for (int i = 0; i < friends.size(); i++) {
if (friends.get(i).equals(formerFriend)) {
friends.remove(i);
break;
} else if (!friends.get(i).equals(formerFriend) && i == friends.size() - 1) {
System.out.println("That person is not in your friends list.");
}
}
}
}
ArrayList<FacebookUser> getFriends() {
ArrayList<FacebookUser> friendsCopy = new ArrayList<FacebookUser>();
for (int i = 0; i < friends.size(); i++) {
friendsCopy.add(friends.get(i));
}
return friendsCopy;
}
}
UserAccount.java
public abstract class UserAccount {
private String username;
private String password;
private boolean active;
public UserAccount(String username, String password) {
this.username = username;
this.password = password;
active = true;
}
public boolean checkPassword(String password) {
if (password.equals(this.password)) {
return true;
} else {
return false;
}
}
public void deactivateAccount() {
active = false;
}
public String toString() {
return username;
}
public boolean checkActive() {
if (active == true) {
return true;
} else {
return false;
}
}
public abstract void getPasswordHelp();
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((username == null) ? 0 : username.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserAccount other = (UserAccount) obj;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
}
Execution:
0
1
That person is already in your friends list.
2
That person is already in your friends list.
3
That person is already in your friends list.
[Michael, Amy, Eugene]
That person is not in your friends list.
[Amy, Eugene]
Password Hint: p1
Password Hint: p4
You're comparing against size() in your for loop, even though you are also potentially adding items to the list in the loop, so you end up comparing the item against itself on the last iteration.
for (int i = 0; i < friends.size(); i++) { // result of size() will change
if (friends.get(i).equals(newFriend)) {
System.out.println("That person is already in your friends list.");
break;
} else if (!friends.get(i).equals(newFriend) && i == friends.size() - 1) {
friends.add(newFriend);
}
}
You can just extract the result of calling size() so that it doesn't change when you add a new item. Or you could also break from the loop after adding the item.
Save size:
int size = friends.size();
for (int i = 0; i < size; i++) {
if (friends.get(i).equals(newFriend)) {
System.out.println("That person is already in your friends list.");
break;
} else if (!friends.get(i).equals(newFriend) && i == friends.size() - 1) {
friends.add(newFriend);
}
}
Or, probably better, use break once you've decided that you should add the item:
for (int i = 0; i < friends.size(); i++) {
if (friends.get(i).equals(newFriend)) {
System.out.println("That person is already in your friends list.");
break;
} else if (!friends.get(i).equals(newFriend) && i == friends.size() - 1) {
friends.add(newFriend);
break;
}
}
And then, an altogether better solution might be to avoid the loop and use contains instead:
void friend(FacebookUser newFriend) {
System.out.println(friends.size());
if (friends.contains(newFriend)) {
System.out.println("That person is already in your friends list.");
return;
}
friends.add(newFriend);
}
Your loop is wrong:
for (int i = 0; i < friends.size(); i++) {
if (friends.get(i).equals(newFriend)) {
System.out.println("That person is already in your friends list.");
break;
} else if (!friends.get(i).equals(newFriend) && i == friends.size() - 1 ) {
friends.add(newFriend);
}
}
You are iterating through the friends list, then you add it when you get to the end, then the friends list becomes one larger, so then you compare with the one you just added, and it says it is already there.
You want this:
boolean alreadyThere = false;
for (int i = 0; i < friends.size(); i++) {
if (friends.get(i).equals(newFriend)) {
System.out.println("That person is already in your friends list.");
alreadyThere = true;
break;
}
}
if(!alreadyThere) {
friends.add(newFriend);
}
More simply, it could be this:
if(friends.contains(newFriend)) {
System.out.println("That person is already in your friends list.");
} else {
friends.add(newFriend);
}
You are going in the right direction, but the iteration over the last added friend is the problem.
A quick fix could be breaking the loop after adding:
friends.add(newFriend);
break;
But it isn't a proper solution. We can use the contains in here:
if (friends.contains(newFriend)) {
System.out.println("That person is already in your friends list.");
return;
}
friends.add(newFriend);
When you add newFriend to the list, its size grows and so the loop execute one more time actually comparing newFriend to itself and so displaying the message.
The quick fix is to add a break; but this make things quite complex...
To me you could just write:
if (friends.contains(newFriend)) {
System.out.println("That person is already in your friends list.");
} else {
friends.add(newFriend)
}
without having to loop manually on the list elements.
But an even simpler solution would be to implement equals/hashCode for FacebookUser (required anyway for proper use of contains and finding the right friend) and use a Set of friends rather than a list. The Set structure always ensure there no duplicate and would perform much faster if there was to be many friends.
private Set<FacebookUser> friends = new HashSet<FacebookUser>();
[...]
if (!friends.add(newFriend)) {
System.out.println("That person is already in your friends list.");
}

JFrame submit button confirm

I have a submit button in my program/JFrame it checks for validations and brings up error messages and then another form pops up and has all entered details:
private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {
//VALIDATIONS-----------------------------------------------------------
if(txtName.getText().trim().equals(""))
{
JOptionPane.showMessageDialog(null, "Must have name");
jlblNameVer.setVisible(true);
}
else
{
jlblNameVer.setVisible(false);
}
//ID VERIFICATION
if (txtIdNumber.getText().trim().equals(""))
{
JOptionPane.showMessageDialog(null, "Photo Id must not be emplty");
}
//EMAIL VALIDATION
if(txtEmail==null ||txtEmail.getText().length() < 10|| txtEmail.getText()== null ||!(txtEmail.getText().trim().contains("#") && txtEmail.getText().trim().contains(".")))
{
JOptionPane.showMessageDialog(null, "Invalid Email");
}
//Phone Number Validation
if(txtPhoneNum.getText().length() < 10)
{
JOptionPane.showMessageDialog(null, "Must atleast 10 characters");
}
//COMBOBOX VALIDATIONS
if(cmbStayDuration.getSelectedIndex() == -1)
{
JOptionPane.showMessageDialog(null, "Please select stay duration");
}
//Photo ID
if(cmbPhotoId.getSelectedIndex() == -1)
{
JOptionPane.showMessageDialog(null, "Please select Photo ID type");
}
//Popup form
jfrmDetails nf1 = new jfrmDetails();
jfrmDetails.txtRoomTypef2.setText(this.cmbRoomType.getSelectedItem().toString());
jfrmDetails.txtRoomNumf2.setText(this.cmbRoomNumber.getSelectedItem().toString());
jfrmDetails.txtCheckIn.setText(this.ftxtCheckinDate.getText());
jfrmDetails.txtCheckOut.setText(this.txtCheckOut.getText());
jfrmDetails.txtName.setText(this.txtName.getText());
jfrmDetails.txtIdType.setText(this.cmbPhotoId.getSelectedItem().toString());
jfrmDetails.txtIdNum.setText(this.txtIdNumber.getText());
jfrmDetails.txtPhoneNum.setText(this.txtPhoneNum.getText());
jfrmDetails.txtEmail.setText(this.txtEmail.getText());
nf1.setVisible(true);
}
The problem is even when these validations are wrong the form will pop up anyway
If any of the validations are incorrect I don't want the popup form to show, what must I do?
You either need to restructure you if blocks into a if-else if-else block, so that last (else) condition would show the new view or use a boolean field which determines if the validation passed or not, for example...
boolean passed = true;
if (txtName.getText().trim().equals("")) {
JOptionPane.showMessageDialog(null, "Must have name");
jlblNameVer.setVisible(true);
passed = false;
} else {
jlblNameVer.setVisible(false);
}
//ID VERIFICATION
if (txtIdNumber.getText().trim().equals("")) {
JOptionPane.showMessageDialog(null, "Photo Id must not be emplty");
passed = false;
}
//EMAIL VALIDATION
if (txtEmail == null || txtEmail.getText().length() < 10 || txtEmail.getText() == null || !(txtEmail.getText().trim().contains("#") && txtEmail.getText().trim().contains("."))) {
JOptionPane.showMessageDialog(null, "Invalid Email");
passed = false;
}
//Phone Number Validation
if (txtPhoneNum.getText().length() < 10) {
JOptionPane.showMessageDialog(null, "Must atleast 10 characters");
passed = false;
}
//COMBOBOX VALIDATIONS
if (cmbStayDuration.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(null, "Please select stay duration");
passed = false;
}
//Photo ID
if (cmbPhotoId.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(null, "Please select Photo ID type");
passed = false;
}
if (passed) {
//Popup form
jfrmDetails nf1 = new jfrmDetails();
jfrmDetails.txtRoomTypef2.setText(this.cmbRoomType.getSelectedItem().toString());
jfrmDetails.txtRoomNumf2.setText(this.cmbRoomNumber.getSelectedItem().toString());
jfrmDetails.txtCheckIn.setText(this.ftxtCheckinDate.getText());
jfrmDetails.txtCheckOut.setText(this.txtCheckOut.getText());
jfrmDetails.txtName.setText(this.txtName.getText());
jfrmDetails.txtIdType.setText(this.cmbPhotoId.getSelectedItem().toString());
jfrmDetails.txtIdNum.setText(this.txtIdNumber.getText());
jfrmDetails.txtPhoneNum.setText(this.txtPhoneNum.getText());
jfrmDetails.txtEmail.setText(this.txtEmail.getText());
nf1.setVisible(true);
}
or
if (txtName.getText().trim().equals("")) {
JOptionPane.showMessageDialog(null, "Must have name");
jlblNameVer.setVisible(true);
} else {
jlblNameVer.setVisible(false);
//ID VERIFICATION
if (txtIdNumber.getText().trim().equals("")) {
JOptionPane.showMessageDialog(null, "Photo Id must not be emplty");
passed = false;
} else if (txtEmail == null || txtEmail.getText().length() < 10 || txtEmail.getText() == null || !(txtEmail.getText().trim().contains("#") && txtEmail.getText().trim().contains("."))) {
JOptionPane.showMessageDialog(null, "Invalid Email");
passed = false;
} else if (txtPhoneNum.getText().length() < 10) {
JOptionPane.showMessageDialog(null, "Must atleast 10 characters");
passed = false;
} else if (cmbStayDuration.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(null, "Please select stay duration");
passed = false;
} else if (cmbPhotoId.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(null, "Please select Photo ID type");
passed = false;
} else {
//Popup form
jfrmDetails nf1 = new jfrmDetails();
jfrmDetails.txtRoomTypef2.setText(this.cmbRoomType.getSelectedItem().toString());
jfrmDetails.txtRoomNumf2.setText(this.cmbRoomNumber.getSelectedItem().toString());
jfrmDetails.txtCheckIn.setText(this.ftxtCheckinDate.getText());
jfrmDetails.txtCheckOut.setText(this.txtCheckOut.getText());
jfrmDetails.txtName.setText(this.txtName.getText());
jfrmDetails.txtIdType.setText(this.cmbPhotoId.getSelectedItem().toString());
jfrmDetails.txtIdNum.setText(this.txtIdNumber.getText());
jfrmDetails.txtPhoneNum.setText(this.txtPhoneNum.getText());
jfrmDetails.txtEmail.setText(this.txtEmail.getText());
nf1.setVisible(true);
}
}
You should also have a look at The Use of Multiple JFrames, Good/Bad Practice? and maybe consider using a CardLayout instead, but this will depend on your underlying needs
You could also have a look at Validating Input, which would allow you to do post validation of your fields when the lose focus

Printing datastructure from input doesn't work

I'm trying to create a program which prints a datastructure from the input. The input and output looks like this: http://puu.sh/kDMc9/2d46462d4d.png. So for example, in the first test case: the first line indicates how many lines will follow in that case. Then if it's the number 1 as the first number on a line it means that you want to add elements to stack/queue/priority-queue and 2 means you want to take out an element, so the second number on a line is the value. Then the output prints if it's stack,queue, priority-queue, impossible or not sure(can be more than one)
This is the code I have now:
import java.util.PriorityQueue;
import java.util.Scanner;
public class DataStructure {
public static void main(String[] args)
{
while(calculate());
}
private static boolean calculate()
{
Scanner input = new Scanner(System.in);
int numberOfRowsPerCase = input.nextInt();
Stack<Integer> stack = new Stack<Integer>();
Queue<Integer> queue = new Queue<Integer>();
PriorityQueue<Integer> prioQueue = new PriorityQueue<Integer>();
boolean stackBool = true;
boolean queueBool = true;
boolean prioQueueBool = true;
int next;
for(int i = 0; i < numberOfRowsPerCase; i++)
{
next = input.nextInt();
if(next == 1)
{
next = input.nextInt();
stack.push(next);
queue.enqueue(next);
prioQueue.add(next);
}
else if(next == 2)
{
next = input.nextInt();
if(!stack.pop().equals(next))
{
stackBool = false;
}
else if(!queue.dequeue().equals(next))
{
queueBool = false;
}
else if(!prioQueue.poll().equals(next))
{
prioQueueBool = false;
}
}
if(stackBool == true)
{
System.out.println("stack");
}
else if(queueBool == true)
{
System.out.println("queue");
}
else if(prioQueueBool == true)
{
System.out.println("priority queue");
}
else if((stackBool == true && queueBool == true) || (queueBool == true && prioQueueBool == true) || (stackBool == true && prioQueueBool == true))
{
System.out.println("not sure");
}
else
{
System.out.println("impossible");
}
}
//Check EOF
String in;
in = input.nextLine();
in = input.nextLine();
if(in.equals(""))
{
return false;
}
return true;
}
}
But when I run the test-case on the picture above, my program prints this: https://ideone.com/mIO1bs which is wrong. I can't find why it does that, can anyone else here maybe see?
Assuming that your logic setting the boolean flags is correct then this part
if(stackBool == true)
{
System.out.println("stack");
}
...
else if((stackBool == true && queueBool == true) || (queueBool == true && prioQueueBool == true) || (stackBool == true && prioQueueBool == true))
{
System.out.println("not sure");
}
will never work as intended because parts of the second condition were already caught by the first condition.
The better suggestion is to come up with a clearer way of representing this. A suggestion that will still probably work is to put your more complicated if statements at the start of the if-else chain.
Disregarding above assumption:
if(!stack.pop().equals(next))
{
stackBool = false;
}
else if(!queue.dequeue().equals(next))
{
queueBool = false;
}
else if(!prioQueue.poll().equals(next))
{
prioQueueBool = false;
}
These should not be elses, they're all completely independent.

Android EditText validation

I have two EditText like editText1 and editText2.
I am taking input from EditText to name1 and name2.
Now I want to validate that the EditText are not empty before clicking on ok button.
For this I used:
if(editText1==NULL && editText2==NULL) {
textView.setText("please enter Names");
} else {
other code;
}
But its not validating, and with empty EditText it is showing result on clicking ok button.
I have also tried in this way:
if(name1==NULL && name2==NULL) {
textView.setText("please enter Names");
} else {
other code;
}
What to do?
Try this:
if(editText1.getText().toString().trim().equals("")
&& editText2.getText().toString().trim().equals(""))
{
textView.setText("Please enter Names");
}
else
{
// other code
}
Please use:
if(name1.compareTo("") == 0 || name2.compareTo("") == 0) {
// Your piece of code for example
Toast toast=Toast.makeText(getApplicationContext(), "ENTER NAMES", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
} else {
// Your code
}
This will work definitely for sure.
Try like this name1.equals("") in place of name1==NULL
if(name1.equals("") && name2.equals(""))
{
textView.setText("please enter Names");
}
else
{
other code;
}
if(name1.compareTo("") == 0 || name2.compareTo("") == 0)
{
// Your piece of code for example
}
you can use:
if(name.compareTo("") == 0 || name.compareTo(null) == 0) {}
This works very well for me, try this
if(editText1.getText().toString().length == 0 && editText2.getText().toString().length == 0)
{
textView.setText("Please enter names");
}
else
{
//some other actions to perform
}
if(editText1.getText().toString().length() > 0 && editText2.getText().toString().length() > 0)
{
textView.setText("Please enter Names");
}
else
{
// Other code
}

Why is this not returning true?

public void check() {
if (particle < 0) {
if (point[3].equals(point[3]) == true) {
check = true;
}
check = false;
}
}
Shouldn't point[3] be equal to itself? making it true?
Maybe you mean to say else check = false?
public void check(){
if(particle < 0){
if(point[3].equals(point[3]) == true){
check = true;
}else{
check = false;
}
}
//here it is true
}
or simply:
public void check(){
if(particle < 0){
check = point[3].equals(point[3]);
}
//here it is true
}
You must return after check = true; from the function, or use else. Else it will fall down from the if and return false always
if (...) {
check = true;
}
else {
check = false;
}
public void check(){
if(particle < 0){
if(point[3].equals(point[3]) == true){
check = true;
}else{
check = false;
}
}
}
Try this:
public boolean check() {
if (particle < 0) {
return point[3].equals(point[3]);
} else {
return false;
}
}
what about particle?
by convention point ought to be equal to itself, but you could always implement it otherwise.
but of course, the other reply is correct, this function will always end with check=false

Categories