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";
}
Related
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; &, > 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 & and > 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)
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.
I have a form and I put the forms data in an intent and then start a new activity and send the data with the intent, but I wanna do a check if the strings are empty I should display and error message. If the strings are not empty the activity can be started.
I've tried the following code but it doesn't seem to be working. If the field is empty it just starts the other activity
(I've tried with only 1 field for now, because I don't know how to to it for multiple fields)
//getting the field values
String firstname = editTextFirstname.getText().toString();
String lastname = editTextLastname.getText().toString();
String amount = editTextBedrag.getText().toString();
String timespan = spinnerPeriode.getSelectedItem().toString();
String iban = editTextIBAN.getText().toString();
if(firstname != null) {
//putting data in the intent
intent.putExtra(FIRSTNAME, firstname);
intent.putExtra(LASTNAME, lastname);
intent.putExtra(AMOUNT, amount);
intent.putExtra(TIMESPAN, timespan);
intent.putExtra(IBAN, iban);
startActivity(intent);
}else{
Toast.makeText(MainActivity.this, "Oops, you forgot to fill in some fields!", Toast.LENGTH_SHORT).show();
}
A cleaner way to do this is
public static boolean isAnyStringNullOrEmpty(String... strings) {
for (String s : strings)
if (s == null || s.isEmpty())
return true;
return false;
}
Then you can call it like this
if (isAnyStringNullOrEmpty(firstname, lastname, amount, timespan, iban)) {
Toast.makeText(MainActivity.this, "Oops, you forgot to fill in some fields!", Toast.LENGTH_SHORT).show();
} else {
}
Using apache commons, we can do this as:
boolean valid = StringUtils.isNoneEmpty(firstname, lastname, amount, timespan, iban)
Change
if(firstname != null)
to
if(!TextUtils.isEmpty(firstname) && !TextUtils.isEmpty(lastname) &&
!TextUtils.isEmpty(amount) &&!TextUtils.isEmpty(timespan) &&
!TextUtils.isEmpty(iban))
Java 8 + Apache Commons Lang only:
String firstname = editTextFirstname.getText().toString();
String lastname = editTextLastname.getText().toString();
String amount = editTextBedrag.getText().toString();
String timespan = spinnerPeriode.getSelectedItem().toString();
String iban = editTextIBAN.getText().toString();
boolean valid = Stream.of(firstname, lastname, amount, timespan, iban)
.allMatch(StringUtils::isNotBlank);
if(firstname != null && lastname != null && amount != null && timespan != null
&& iban != null & firstname.trim().isEmpty() && !lastname.trim().isEmpty() &&
!amount .trim().isEmpty() && !timespan.trim().isEmpty() && !iban.trim().isEmpty())
Using Java Stream API:
private boolean anyBlank(String...strings) {
return Stream.of(strings).anyMatch(string -> isBlank(string));
}
How to get value of selected radioButton?
I tried using buttonGroup1.getSelection().getActionCommand() (as posted in some of answers here) but it is not working.
Also, i am temporarily using this code but i want to know is this a good practice or not?
//Consider that maleRButton and femaleRButton are two radioButtons of
//same buttonGroup
String getGender()
{
if(maleRButton.isSelected())
{
return "Male";
}
else if(femaleRButton.isSelected())
{
return "Female";
}
else
{
return null;
}
}
I tried using buttonGroup1.getSelection().getActionCommand()
That approach will work, but for some reason it looks like you manually need to set the action command when you create the button. For example:
JRadioButton maleButton = new JRadioButton( "Male" );
maleButton.setActionCommand( maleButton.getText() );
This acutally seems like a bit of a bug to me since usually the action command defaults to the text if the action command is not set.
If you have several buttons you probably should do it this way :
String getSelectedButton()
{
for (Enumeration<AbstractButton> buttons = buttonGroup1.getElements(); buttons.hasMoreElements();) {
AbstractButton button = buttons.nextElement();
if (button.isSelected()) {
return button.getText();
}
}
return null;
}
String gender=group.getSelection().getActionCommand();
It will work but it show null value.
int selectedRadioButtonID = radio_group.getCheckedRadioButtonId();
// If nothing is selected from Radio Group, then it return -1
if (selectedRadioButtonID != -1) {
RadioButton selectedRadioButton = findViewById(selectedRadioButtonID);
String selectedRadioButtonText = selectedRadioButton.getText().toString();
answerList.add(selectedRadioButtonText);
} else {
Toast.makeText(this, "select radio button", Toast.LENGTH_SHORT).show();
return false;
}
For Deatils, check this
I have a field that I am trying to set the length of 25 to by using StringBuilder and then populate it with string values in specific positions within that field. However, when I get a print out of the values in that field the value looks like this:
M0
Obviously I am needing to remove the "�" values from that field. Any help/direction would be appreciated.
Here is my code:
String b44 = toRequestIsoMessage.getString(B44_ADD_RESPONSE_DATA.bitId);
if (b44 == null) {
// ***** 20130604 MS - Told Ralph since that position 1 is space filled initially in the request to the CORE so that he can modify for the AVS. *****
String avsValue = " ";
try {
StringBuilder revB44Value = new StringBuilder();
revB44Value.setLength(25);
revB44Value.insert(0, avsValue);
if (decision.cidResponse.responseCode != null) {
revB44Value.insert(1, decision.cidResponse.responseCode);
} else {
revB44Value.insert(1, " ");
}
if (decision.cvvResponse.responseCode != null) {
revB44Value.insert(13, decision.cvvResponse.responseCode);
} else {
revB44Value.insert(13, " ");
}
String revB44 = revB44Value.toString();
toRequestIsoMessage.setString(B44_ADD_RESPONSE_DATA.bitId, revB44Value.toString());
} catch (InternalISOMsgException e) {
LOGGER.info(FormatData.fullStackTrace(e));
}
}