Why the if condition runs the other way - java

the value passed fromjsonObject.getString("firstName"); to firstNameValidateUser is null as it doesn't have any value, I need to run the following code which contain String firstName=jsonObject.getString("firstName");.... till returnedUser = new User(firstName, lastName, user.userName, user.password, birthDate, position,qualification,email); when the value of firstNameValidateUser is null. How do I check it,I have used the if condition to check if the firstNameValidateUseris null ,but from the output it seems like it is working the other way round. Is there something wrong with my if condition, or if I have done any other mistake please notify me.. please help me to fix this. Thank you in advance.
firstNameValidateUser=jsonObject.getString("firstName");
// if there are no details are send through the JSON object,
Log.e("jsonObjectlength",jsonObject.length()+"");
Log.e("firstName",firstNameValidateUser);
String usedToCheck=null;
if (firstNameValidateUser!=null && !firstNameValidateUser.isEmpty()) {
Log.e("firstName","firstName is not null");
String firstName = jsonObject.getString("firstName");
String lastName = jsonObject.getString("lastName");
//String username=jsonObject.getString("username");
//String password=jsonObject.getString("password");
String position=jsonObject.getString("position");
String qualification=jsonObject.getString("qualification");
String birthDate=jsonObject.getString("birthDate");
String email=jsonObject.getString("email");
returnedUser = new User(firstName, lastName, user.userName, user.password, birthDate, position,qualification,email);
//values are sent to the returnedUser Object
} else {
Log.e("is Empty","firstName is null");
returnedUser = null;
}

The most easiest way to check is using native API
if (jsonObject.isNull("firstName")) {
Log.e("is Empty","firstName is null");
} else {
Log.e("firstName","firstName is not null");
}
Refer to android API
http://developer.android.com/reference/org/json/JSONObject.html#isNull(java.lang.String)

Wrong condition:
Try:
if (firstNameValidateUser!=null || !firstNameValidateUser.isEmpty()) {
// Rest of your code.
}
Reason:
True && True == True
True && False == False
So from 2nd case, if the second value will be False, it won't enter the if condition.

So after the code edit it seems fine, however if the error still persists then i suggest you check if the following line actually returns something at all.
firstNameValidateUser=jsonObject.getString("firstName");
(Just let it show up in the console using: console.log() )
If that returns nothing the problem is probably in the code that either retrieves the string or the code that sets the string.

Related

How to validate Username in Login activity

I'm very new to this Android, so I'm very sorry if this question will make you laugh.
Recently I'm trying an Android tutorial about 'Creating Login Screen With SQLite'. I'm successfully creating that Login along with Register and with SQLite DB. What I want to know is how to change the Text Input from Email to Username.
I have searched the code for how to changing the validation from Email to Username but still don't get that.
FYI, I have created the Username table in the DB.
public boolean validate() {
boolean valid = false;
// Get values from EditText fields
String Email = editTextUsername.getText().toString();
String Password = editTextPassword.getText().toString();
// Handling validation for Email Address
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()){
valid = false;
textInputLayoutUsername.setError("Input Correct Username");
} else {
valid = true;
textInputLayoutUsername.setError(null);
}
}
Here is my login screen.
I had to change the text from Email to Username on that EditText. But when I run it, the EditText always validate the email. I think there's something to change in this line.
!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()
Thanks before for all the help, I really appreciate it.
Your current implementation is validating the input from the editTextUsername and trying to validate if the input is a valid email address. If you do not want that, just remove the validation for this specific view in your code like the following.
public boolean validate() {
boolean valid = false;
//Get values from EditText fields
String userName = editTextUsername.getText().toString();
String Password = editTextPassword.getText().toString();
// Handle the validation for the user name.
// Let us assume, you just want to validate that the user has put something as a user name
if(userName.length() > 0) {
valid = true;
textInputLayoutUsername.setError(null);
} else {
valid = false;
textInputLayoutUsername.setError("Please provide the user name.");
}
}
You can always change the logic of your validation. I just showed an example. I hope that helps!
Just use plain text field and use regular express in backend code ( [A-Za-z0-9]* ) to validate your input.
//it's saying if email contains alpnum char and ._- of length min 3 i.e >=3 then its true
if(Email.matches(^[a-zA-Z0-9._-]{3,}$)) {
// valid input code
} else {
// invalid input code
}
please check the blow code.
public boolean validate() {
//Get values from EditText fields
String userName = editTextUsername.getText().toString().trim();
String Password = editTextPassword.getText().toString().trim();
if (userName.isEmpty()) {
//set error message
return false;
} else if (Password.isEmpty()) {
//set error message
return false;
} else if (Password.length()<6 || Password.length()>15) {
// set error message
return false;
}
return true;
}

"Cast" a String Attribute to String Java [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have a little problem with Attributes. I am currently working on a project that parses emails from an LDAP server into the Java application that will be doing some interesting stuff with emails in the future.
I am currently having this code that takes emails from users on LDAP and it needs to put emails in the User class as seen in my code:
[some code here, TRY CATCH is also included]
LdapContext ctx = new InitialLdapContext(env, null);
ctx.setRequestControls(null);
NamingEnumeration<?> namingEnum2 = ctx.search("[path to the server]", "(objectClass=user)", getSimpleSearchControls());
System.out.println("Test: print emails from whole DIRECOTRY: \n");
while (namingEnum2.hasMore()) {
SearchResult result = (SearchResult) namingEnum2.next();
Attributes attrs = result.getAttributes();
System.out.println(attrs.get("mail"));
/** This line above works fine, but every time there is no email
in User info, it prints "null" in some cases when there is
no email, which is not perfect. But this is just here to see
if everything works and indeed it does.**/
/**User Class accepts a String parameter, checks if it's empty
and all that, does some checking and etc... BUT! attrs.get("mail")
is an Attribute, NOT a String. And I need to somehow "cast" this
attribute to a String, so I can work with it.**/
User user = new User(attrs.get("mail")); //error yet,because the parameter is not a String.
User user = new User(attrs.get("mail").toString());//gives an expeption.
/** And I know that there is a toString() method in Attribute Class,
but it doesn't work, it gives an "java.lang.NullPointerException"
exception when I use it as attrs.get("mail").toString() **/
}
Here is User class's constructor:
public User(String mail){
eMail = "NO EMAIL!";
if (mail != null && !mail.isEmpty()){
eMail = mail;
}
else
{
eMail = "NO EMAIL!";
}
}
try this
User user = new User(attrs.get("mail")!=null?attrs.get("mail").toString():null);
First you need to check that given attribute exists by using != null (e.g. using Objects.toString which does that inside, or manual if) check, and then use either toString on the Attribute, just like println does inside:
User user = new User(Objects.toString(attrs.get("mail")));
Or you can also use (to retrieve a single value in the attribute, if you have many you need to use getAll):
Object mail = null;
if (attrs.get("mail") != null) {
mail = attrs.get("mail").get();
}
User user = new User(mail.toString());

JUnit Testing equivalence partitioning, where parameters are being received from JTextField rather than being passed into method

Ok so Im a bit confused and cant find a clear answer to my question.What I want to do is check if an input condition specifies a range of values ie. Greater than one char.I have already handled for this in my code but need to create the JUnit for some testing as part of a college assignment.I will post my code here.
This is the method I want to check and it is in a class called AccountCreation.
or am i on the wrong path using JUnit??
Thanks
public void CreateAccountButtonClicked()
{
//check database for username multiple entries
DbCheck check = new DbCheck();
String userName = textField.getText();
String password = passwordField.getText();
//if statement to make sure username and password have at least one character
if(userName.length()<1 ||password.length()<1)
{
JOptionPane.showMessageDialog(null, "Please Enter at least one character in each field");
}
else{
boolean checkCredentials = check.checkAcc(userName);
if(checkCredentials == false)
{
int score=0;
DbConnect connect = new DbConnect();
connect.setData(userName,password,score);
this.setVisible(false);
new GameSelection().setVisible(true);
}
else
{
//inform user if user name is already taken.
JOptionPane.showMessageDialog(null, "User name already exists");
}
}
}
}

Using one Input data in two tasks

Is there a way to use one Input data in two tasks? I have a program that has to check if an Email matches a particular pattern and at the end if an email is correct the program prints it. In my case I have to write the email twice, one time so an email can be stored in a variable email = In.readLine(); and the second time so it can be checked vname = In.readIdentifier(); and I want to write it just once.
Out.print("Please enter an Email-Adress: ");
email = In.readLine();
name = In.readIdentifier();
if (!In.done()) {
Out.println("Error : False name");
return;
}
Change your readIdentifier() function so you can pass the previously read "email" variable to it instead of reading from In again.
You dont need to read email twice. So your custom code:
email = In.readLine();
name = In.readIdentifier();
can be changed to:
email = In.readLine();
//name = In.readIdentifier();
and further in your business logic you could just use email instead.

How do I check for the null value in Java?

How to look for the value whether it is null or not in JSP. E.g. in below I want to check the description column in pipe table for null values.
String Query1 = "SELECT description FROM pipe where pipe_id='" + id+"' and version_id=2";
SQLResult = SQLStatement.executeQuery(Query1);
SQLResult.first();
description = SQLResult.getString("description");
if(description=="")
{
json_string=json_string+"&desc="+description;
out.println("not null");
} else
{
json_string=json_string;
out.println("null");
}
Well: if (description != null && !description.isEmpty()) ... however are you writing this code within a JSP ? That seems wrong. You should probably do this stuff within a servlet and pass the description as an request attribute to a jsp.
Or you can use StringUtils.isNotEmpty(description).
If you are really using jsp, you should store description in a request attribute and then use <c:if test="${empty description}">.
I use this personal method:
public static boolean isNullOrEmpty(Object obj) {
if (obj == null || obj.toString().length() < 1 || obj.toString().equals(""))
return true;
return false;
}

Categories