IF condition not working with Android CheckBox - java

if ((Problem != null && !notokcheckbox.isChecked()) || (Problem!=null && !ressolvedcheckbox.isChecked())) {
Toast.makeText(getActivity(), "Enable Ok Or Not/Ok", 100000).show();
} else {
Toast.makeText(getActivity(), "Sucess", 100000).show();
}
I am trying to apply validation I have two check Box notokcheckbox and ressolvedcheckbox.
if Problem != null and nither notokcheckbox, ressolvedcheckbox is not checked then it should display Enable Ok Or Not/Ok
or
if Problem != null or either notokcheckbox or ressolvedcheckbox is enable then it should Print Sucess.
while I am trying it with single check Box i mean its working fine but not with both.
Can u please tell me how to apply with two check Box:
if (Problem != null && !notokcheckbox.isChecked()) {
Toast.makeText(getActivity(), "Enable Ok Or Not/Ok", 100000).show();
} else {
Toast.makeText(getActivity(), "Sucess", 100000).show();
}
working fine.
please suggest me how to fix it.

If I understand correctly, you want to display the "Enable Ok Or Not/Ok" text when both are unchecked, and otherwise "Success" (when either or both are enabled). Try this:
if (Problem != null && (!notokcheckbox.isChecked() && !ressolvedcheckbox.isChecked())) {
Toast.makeText(getActivity(), "Enable Ok Or Not/Ok", 100000)
.show();
}
else {
Toast.makeText(getActivity(), "Sucess", 100000)
.show();
}
If you instead mean it should display the "Enable Ok Or Not/Ok" text when neither OR both are enabled, and "Success" if just one is enabled, try this:
if (Problem != null && !(notokcheckbox.isChecked() ^ ressolvedcheckbox.isChecked())) {
Toast.makeText(getActivity(), "Enable Ok Or Not/Ok", 100000)
.show();
}
else {
Toast.makeText(getActivity(), "Sucess", 100000)
.show();
}
Or better yet, use RadioButtons so only one option can be selected..

Simplifying:
if (problem != null && (!notOkCheckBox.isChecked() || !ressolvedCheckBox.isChecked()) {
...
} else {
...
}
The expression below is true if problem is null and one of the two (or both of them) checkboxes is checked.
p.s. pay attention to the case of your variables, you should respect java variable naming convention.

Related

Java checkbox with AND operator

Please, I want to use the AND operator with checkbox in creating different options.
if (chkd.isSelected()){
lbl.setText("hello");
}
else if (chkd.isSelected() && chkm.isSelected()){
lbl.setText("cool");
}
Please, what's the best approach to do this. I am using Eclipse for Java.
As written, assuming chkd and chkm are defined won't work because if the if statement is true, the else if won't execute.
Try this instead:
if (chkd.isSelected()) {
if (chkm.isSelected()) {
lbl.setText("cool");
} else {
lbl.setText("hello");
}
}
What's happening is we're checking chkd is true, we then check to see if chkm is true we're cool, otherwise, we're hello.
Alternatively you can turn around your if statement.
So checking first for the (a && b) Statement will give you the cool value. If the && is not true, your other Statement (hello) will be displayed.
if (chkd.isSelected() && chkm.isSelected()) {
lbl.setText("cool");
} else if {
lbl.setText("hello");
}

JAVA Comparing two Strings isn't working

So here's a snippet of code I'm working on:
String direction = s.readLine();
System.out.println(direction);
if (direction.equals("up") != true && direction.equals("down") != true &&
direction.equals("left") != true && direction.equals("right") &&
direction.equals(null) != true) {
System.out.println("Invalid Solution file");
System.exit(0);
}
What it is supposed to do is read a line from a text file (using a BufferedReader) and then if the line isn't either a valid direction or blank then it should print "Invalid Solution" and exit.
The problem is that no matter what the direction string is the if statement still runs. I put in a println to check whether the direction was being read correctly but it seems absolutely fine. So why isn't the code working as intended?
Part of your problem is readability. Fix that and your problem is 90% solved:
private static List<String> DIRECTIONS = Arrays.asList("up", "down", "left", "right");
then
if (!DIRECTIONS.contains(direction)) {
System.out.println("Invalid Solution file");
System.exit(0);
}
The other 10% was how to check for null, which is direction == null, but if you use this code you don't need to, because contains(null) will conveniently return false.
You code is much more complex than it is needs to.
Consider this instead:
Set<String> validDirections = new HashSet<>(Arrays.asList("up", "down", ...
if (validDirections.contain(direction.toLowerCase()) {
// good ...
} else {
// bad ..
}
You can make validDirections a global constant for example; so it could be used in other places as well.
What I am trying to explain here is: your code is low-level. Low level code is hard to write, read, maintain and extend. Programming is always about creating good abstractions. Or vice versa: if you don't use abstractions, you end up with pretty abstract code, like the one you are showing here!
For example: if you need another direction, you have to put into your already way too complicated if condition. In my solution, you just put it into the statement that builds that Set.
Finally: your error message, is saying nothing. So, that string is bad; but why is it? Wouldn't it be better to at least print the string that caused the error?!
Here && direction.equals("right") I think you have done a mistake since it is on contradiction with the rest :
direction.equals("up") != true &&
direction.equals("down") != true &&
direction.equals("left") != true
You test the negation in the most of conditions but direction.equals("right") tests the affirmation.
Try it , it's the same thing but less verbose and more readable :
if (direction !=null && !direction.equals("up") &&
!direction.equals("down") &&
!direction.equals("left") &&
!direction.equals("right") ){
System.out.println("Invalid Solution file");
System.exit(0);
}
First, you should not use != true with a boolean statement, it is bad form. Rewrite like this:
direction !=null &&
!direction.equals("up") &&
!direction.equals("down") &&
!direction.equals("left") &&
!direction.equals("right")
Your error was that you did not include the != true part on one of your statements within the compound if. Replace with the above code to solve the issue.
I'm confused why you are using !=true when your .equals method already returns a boolean. Try this.
String direction = s.readLine();
System.out.println(direction);
if ( direction!=null && !direction.equals("up") && !direction.equals("down")&& !direction.equals("left")&& direction.equals("right")){
System.out.println("Invalid Solution file");
System.exit(0);
}
Try the following code:
boolean match = false;
if (direction.equals("up"))
{ match = true; }
if (direction.equals("down"))
{ match = true; }
if (direction.equals("left"))
{ match = true; }
if (direction.equals("right"))
{ match = true; }
if (direction.equals(null))
{ match = true; }
if (match == false){
System.out.println("Invalid Solution file");
System.exit(0);
}
You might also want to trim the direction string after reading from file.
The quals method returns a boolean so the result does not need to be compared with the true or false value. Also, I would start with null comparison - boolean expressions in Java are shortened so if this part will be fulfilled rest of the expression is not evaluated. The correct expression might look like this:
 
if (direction == null || (!direction.equals("up") && !direction.equals("down") && !direction.equals("left") && !direction.equals ("right "))) {
}
But this code is not readable. You could use enums or list of Strings like below
List<String> directions = Arrays.asList("up", "down", "left", "right");
String direction = "readValue"
if (!directions.contains(direction)) {
System.out.println("Invalid direction");
System.exit(0)
}

how to check if atleast one checkbox is checked android

This what I have done so far, even though I check all of them I get AlertDialog message.
private void validateCheckBoxes() {
if (toilets.isSelected() || wifi.isSelected() || trolleys.isSelected() || lifts.isSelected()
&& ticketMachine.isSelected() || stepFree.isSelected()) {
saveRecordsToDatabase();
} else {
AlertDialog.Builder facilitiesError = new AlertDialog.Builder(AddStation.this);
facilitiesError.setTitle("Station Facilities are not selected");
facilitiesError.setMessage("Please select at least one facility ");
facilitiesError.setNegativeButton("OK", null);
facilitiesError.create().show();
}
}
By "selected" do you mean "checked"?
if (toilets.isChecked() || wifi.isChecked() || trolleys.isChecked() || lifts.isChecked()
|| ticketMachine.isChecked() || stepFree.isChecked()) {
saveRecordsToDatabase();
}
modify your code:
if (toilets.isSelected() || wifi.isSelected() || trolleys.isSelected() || lifts.isSelected()
|| ticketMachine.isSelected() || stepFree.isSelected()) {
saveRecordsToDatabase();
}
Explanation: you are using all && operators in if statement, which means you get alert message only if all the check boxes are checked.
If you use all || (or) operator, it means you get alert message if at least one checkbox is checked.

Failed text validation

I have a snippet of code that consistently gives me an error:
do {
System.out.println("Choose Role: (Manager, Developer, QA) ");
role = scan.nextLine();
// For testing: ///////////////////////
System.out.println("role is: " + role);
////////////////////////////////////////////////
if (is_numeric(role)) {
System.out.println("Invalid Input.");
continue;
} else if (!role.equalsIgnoreCase("MANAGER") || !role.equalsIgnoreCase("DEVELOPER") || !role.equalsIgnoreCase("QA")) {
System.out.println("Invalid Role");
continue;
} else {
break;
}
} while (true);
I added the "For testing" block just to see, if for some reason there is something happening to the variable role, but its not. No matter how I write manager/developer/qa (whether in caps, small letters, etc) the "Invalid Role" is triggered and the loop goes over again.
Any suggestions?
Logically, this test is wrong
(!role.equalsIgnoreCase("MANAGER") ||
!role.equalsIgnoreCase("DEVELOPER") ||
!role.equalsIgnoreCase("QA"))
Why? Because if the role = "MANAGER", it does not equal "DEVELOPER" (or "QA") and vice-versa. I think you wanted
(!role.equalsIgnoreCase("MANAGER") &&
!role.equalsIgnoreCase("DEVELOPER") &&
!role.equalsIgnoreCase("QA"))
!role.equalsIgnoreCase("MANAGER") || !role.equalsIgnoreCase("DEVELOPER") ||
!role.equalsIgnoreCase("QA")
Is not what you want, replace || with &&.
In your code you're saying: If role is not "MANAGER" OR if role is not "DEVELOPER" OR if role is not "QA".
Due to Short-circuit evaluation, if the first condition is true, the others won't be evaluated because true || anything is always true.
Java if test short circuit for boolean expressions.
Change || to &&
Contrary to what everyone else is saying, if what you're trying to model is "not valid", then don't distribute the negative over each condition and use &&. It's not modelling the right thing. Model "valid", put parentheses around it and negate the whole thing:
if (!(role.equalsIgnoreCase("MANAGER") || role.equalsIgnoreCase("DEVELOPER") ||
role.equalsIgnoreCase("QA"))) {
//...
}
But this is a case where a helper method will improve code clarity greatly. First model what you want to model, not the inverse:
public boolean validRole(String role) {
return role.equalsIgnoreCase("MANAGER") ||
role.equalsIgnoreCase("DEVELOPER") ||
role.equalsIgnoreCase("QA");
}
Then your if statement is hard to get wrong and documents itself:
if (!validRole(role)) {
//...
}

Checking null String in android

I am developing an android application.I am getting a String value as null from webservice. I am fetching the value and storing it in a String variable. Then when I print the value using Log, like Log.i("tag", "````!!!cell >>"+cell);, I an getting null printed in the screen. Now what i need is that I need to check the variable for 'null' and I want to display a textfield with no value if it is 'null'. I am using the following statement for checking
if(!cell.equals(null) || !cell.equals("")) {
_______
} else {
_______
}
But the control is not going inside the else part if the value us 'null'
Please give me a solution.
Thanks in advance.
when cell is null , and you are trying to invoke a method on it, you will hit by a null pointer exception.
I'd say
if(cell !=null && !cell.isEmpty()) {
_______yes, disply
} else {
_______nope, some thing wrong
}
its not equals(null) its
if(cell != null || !cell.isEmpty())
Try TextUtils.html#isEmpty(java.lang.CharSequence)
I would give try this, seems to be working for me!
if(TextUtils.isEmpty(yourString) && yourString == null){
}
else if(!TextUtils.isEmpty(yourString) && yourString != null){
}
If the value of the string is null, !cell.equals("") will evaluate to true and hence it will go in the if part and not the else part as you are using an OR condition.
NULL != "" (Empty string)!!!
Use this :
if (cell != null && cell.trim().length() > 0) {
// do whatever you want
} else {
// the string received is null
}
Android provides a simple utility
TextUtils.isEmpty(<<stringVariable>>);
More details # http://developer.android.com/reference/android/text/TextUtils.html
WORKING !!!
if (string.matches("")&& string.trim().equals("null")){
return false;
}
else{
return true;
}

Categories

Resources