Explanation on what &amp means in code for validating email address - java

I'm trying to write code that validates email address, and I came across the following source code that allows for proper validation of email address, however when I tried implementing the code on android studio, it did not recognize the following coding items; &amp, &gt and !m_matcher
Source Code:
/**
* Method to validate the EditText for valid email address
* #param p_editText The EditText which is to be checked for valid email
* #param p_nullMsg The message that is to be displayed to the user if the text in the EditText is null
* #param p_invalidMsg The message that is to be displayed to the user if the entered email is invalid
* #return true if the entered email is valid, false otherwise
*/
private boolean validateEmail(EditText p_editText, String p_nullMsg, String p_invalidMsg)
{
boolean m_isValid = false;
try
{
if (p_editText != null)
{
if(validateForNull(p_editText,p_nullMsg))
{
Pattern m_pattern = Pattern.compile("([\\w\\-]([\\.\\w])+[\\w]+#([\\w\\-]+\\.)+[A-Za-z]{2,4})");
Matcher m_matcher = m_pattern.matcher(p_editText.getText().toString().trim());
if (!m_matcher.matches() && p_editText.getText().toString().trim().length() > 0)
{
m_isValid = false;
p_editText.setError(p_invalidMsg);
}
else
{
m_isValid = true;
}
}
else
{
m_isValid = false;
}
}
else
{
m_isValid = false;
}
}
catch(Throwable p_e)
{
p_e.printStackTrace(); // Error handling if application crashes
}
return m_isValid;
}
Part 2:
/**
* Method to check if some text is written in the Edittext or not
* #param p_editText The EditText which is to be checked for null string
* #param p_nullMsg The message that is to be displayed to the user if the text in the EditText is null
* #return true if the text in the EditText is not null, false otherwise
*/
private boolean validateForNull(EditText p_editText, String p_nullMsg)
{
boolean m_isValid = false;
try
{
if (p_editText != null && p_nullMsg != null)
{
if (TextUtils.isEmpty(p_editText.getText().toString().trim()))
{
p_editText.setError(p_nullMsg);
m_isValid = false;
}
else
{
m_isValid = true;
}
}
}
catch(Throwable p_e)
{
p_e.printStackTrace(); // Error handling if application crashes
}
return m_isValid;
}
Could someone please explain to me what &amp and &gt is and why android studio does not recognize these items. And finally, why is the exclamation point in this line of code underlined in red **!**m_matcher
Apologies for the long post and thanks in advance!

You need to use && for & & and > instead of > - looks like you've copied from a web page which has HTML encoded the code.
Change this line from:
if (!m_matcher.matches() && p_editText.getText().toString().trim().length() > 0)
to:
if (!m_matcher.matches() && p_editText.getText().toString().trim().length() > 0)

Related

Parse CACM collection in Java

i'm having a problem parsin the CACM collection in java.
The collection has this format:
.I number
.T
title
.A
authors
multiple authors allowed
.W
body
multiple lines of body allowed
I'm trying to extract each of the fields with this extract method:
public static String extract(char campo, String text,Boolean allowEmpty)
{
String[] lines = text.split("\\r?\\n");
/*for(String line:lines)
System.out.println(line);*/
StringBuilder builder = new StringBuilder();
boolean start = false;
boolean end = false;
for(String l:lines)
{
System.out.println(l);
//System.out.println(line.charAt(0));
if((l.charAt(0) == '.') && (l.charAt(1) == campo))
{
System.out.println("Detectado campo "+l.charAt(1));
start = true;
builder.append(l.substring(2)).append("\n");
}
else
{
if(l.charAt(0) == '.')
{
//System.out.println(campo);
break;
}
else if(start)
builder.append(l);
}
}
return builder.toString();
}
But i do not know why, it does only extract the .I field, and i cant get it to work with any other field. I'm clueless in regard to where to correct the code, or if the approximation is logical.
Any clue in this?
Thank you in advance.

sign-up form validations in java

i have a signup page connected to sql database.now i want to have validations in signup page like firstname,lastname,username etc can not be empty using java how can i do that
My code is
String fname=Fname.getText();
String lname=Lname.getText();
String uname=Uname.getText();
String emailid=Emailid.getText();
String contact=Contact.getText();
String pass=String.valueOf(Pass.getPassword());
Connection conn=null;
PreparedStatement pstmt=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/zeeshan","root","sHaNi97426");
pstmt=conn.prepareStatement("Insert into signup1 values(?,?,?,?,?,?)");
pstmt.setString(1,fname);
pstmt.setString(2,lname);
pstmt.setString(3,uname);
pstmt.setString(4,emailid);
pstmt.setString(5,contact);
pstmt.setString(6,pass);
int i=pstmt.executeUpdate();
if(i>0)
{
JOptionPane.showMessageDialog(null,"Successfully Registered");
}
else
{
JOptionPane.showMessageDialog(null,"Error");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
First your question is not direct. Validation occurs before database query. You should not proceed to database Connetction or making any query.
What should you do:
public static boolean nullOrEmpty(String value) {
return value == null || value.trim().equals("") ? true : false;
}
public void yourMethod(){
try{
//YourCode Here
String fname=Fname.getText();
if(nullOrEmpty(fname)){
new throw ValidationException("First name should not be null.");
}
//YourCode Here
}catch(ValidationException e){
System.err.println("Exception:"+e.getMessage());
}
}
Check for every string to validate.
that should not be hard, you can do it with simple if and else like below
if(fname != null && fname.isEmpty()){
throw new Exception(fname+" cannot be empty");
}else if(lname != null && lname.isEmpty()){
throw new Exception(fname+" cannot be empty");
}
.....
as a recommendation you should abstract validation and database access objects . see example of MVC here
You may do it just by downloading a jar named org.apache.commons.lang
Stringutils Class Reference
Sample Code
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
or
StringUtils.isEmpty(obj_String); // Another method to check either null or "";
To check if a String is empty you can use the method .isEmpty(). You'll probably want to use .trim() first, as this removes all the whitespaces at the beginning and ending of the String. For more options check out the full documentation here.

can't delete from getContentResolver().delete

I can't delete a conversation from getContentResolver, I don't know in which part am doing mistakes, as I also searched about these but can't help myself and I also tried different sols which were given on stackoverflow but same result & thanks a lot in advance.
Here is the code:
public static boolean deleteSmsofContact(Context context, String number,
boolean deleteLocked)
{
int result;
if (deleteLocked) {
//changes values
String[] selectionArgs=new String[]{number};
String selection= ""+"address=?";
//
result = context.getContentResolver().delete(Uri.parse("content://sms/"),selection,selectionArgs);
// Log.d("UF","WOW "+result+" " +number);
} else {
result = context.getContentResolver().delete(Constants.URI_SMS,
"address=? AND locked=?", new String[] { number, "1" });
}
if (result > 0) {
return true;
}
return false;
}
Here is the method from which I am calling:
boolean result = Utils.deleteSmsofContact(InboxActivity.this, sms.getNumber(), true);
if (result) {
dataList.remove(threadPosition);
iAdapter.notifyDataSetChanged();
Toast.makeText(InboxActivity.this,"Removed",Toast.LENGTH_LONG).show();
}else
{
Toast.makeText(InboxActivity.this,"cant removed",Toast.LENGTH_LONG).show();
}
Well I posted it but did not get the answer so finally I searched a lot on this and the correct answer is until or unless your app is not set a default you can't delete any sms or whole conversation.
Follow this link it will make your app set a default OR you will be able to delete.

Data validation within data validation

I first want to validate that the user entered a value and to make sure to exit if 'cancel' was pushed. Then, I want to validate that the String releaseDateString is in the correct format at the same time as converting the String to java.sql.Date.
The first validation is taking place but then the JOptionPane carries on repeating itself and does not even consider the try and catch following it.
Here is my method
boolean retry = false;
java.sql.Date releaseDate = null;
String releaseDateString = "";
String title = "";
while (!retry) {
while(!retry){//field is validated to make sure a value was entered and to exit if cancel was pushed
releaseDateString = JOptionPane.showInputDialog("Please input the release date of the movie (yyyy-mm-dd)");
qtd.stringValidation(releaseDateString);
}
try { //the date is validated to make sure it is in the correct format
releaseDate = java.sql.Date.valueOf(releaseDateString);
} catch (Exception e) {
retry = false;
JOptionPane.showMessageDialog(null, "Make sure you enter a date in the format of 'dd-mm-yyy'");
}
}
It links to this method
public static boolean stringValidation(String attribute){
boolean retry = false;
if (attribute == null){
System.exit(0);
}
else if (attribute.equals("")) //if the cancel button is selected or no value was entered into the
{
JOptionPane.showMessageDialog(null, "Make sure you enter a character into the textbox");
}
else {
retry = true;
}
return retry;
}
When you do this,
qtd.stringValidation(releaseDateString);
You aren't assigning the result to retry. I believe you wanted,
retry = qtd.stringValidation(releaseDateString);

How do I catch the null value from my JtextField?

I have a JTExfield and if the user leaves the textfield empty I wanna catch it up and set the string to "NULL"
It works if I write blablabla or whatever into the string and it should do but I also wanna catch if they leave it empty and put the text "NULL" into my file.
I have tried two solutions no one is working :
When user click ok button it performs this:
setPicture(pictureTextField.getText());
which is calling this method :
public void setPicture(String picture) {
if (picture == null) {
picture = "NULL";
}
this.picture = picture;
}
and :
public void setPicture(String picture) {
if (picture == "") {
picture = "NULL";
}
this.picture = picture;
}
So to repeat what I want to do is to set my picture String to "NULL" is the user leaves the textField empty.
Combine the null and empty checks together:
public void setPicture(String picture) {
if (picture == null || picture.isEmpty()) {
picture = "NULL";
}
this.picture = picture;
}
if(pictureTextField.getText().length()>1){
//nothing in text field. Here you can set null
}else {
// text field contains something
}
or try
pictureTextField.getText().equals("")
You can check this in two ways...
1] checks if String is empty...
if ( "".equals(picture.trim()) ) {
picture = "NULL";
}
2] checks if String length is 0...
if ( picture.trim().length() == 0 ) {
picture = "NULL";
}

Categories

Resources