Edit Text to long variable issue? - java

I am working on a timer app, I have an EditText for taking an input number and based on my radio button selected, multiply the input to be equal to long millisInFuture for the CountDownTimer class. but apparently there is something wrong with parsing my EditText as a long. here is the part for RadioGroup:
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == rdSeconds.getId()) {
et_num.setHint("Seconds");
String value = et_num.getText().toString();
//selectedOption is a long variable
selectedOption = Long.parseLong(value) * 1000;
} else {
et_num.setHint("Minutes");
String value = et_num.getText().toString();
selectedOption = Long.parseLong(value) * 60000; //line 102
}
}
});
Here is part of the error it gaves me?
java.lang.NumberFormatException: For input string: ""
at java.lang.Long.parseLong(Long.java:455)
at java.lang.Long.parseLong(Long.java:485)
at com.example.timemachine.MainActivity$2.onCheckedChanged(MainActivity.java:102)

check your editText have proper value before parse long
String value = et_num.getText().toString();
if(value != null && !value.isEmpty())
{
selectedOption = Long.parseLong(value) * 1000;
}

The error is very clear that you parse empty String to type Number. There some way to handle this
You can check the value on your Edit Text as #sasikumar answer like :
if (!yourEditText.getText().toString().equals("")) {
/* Then parse your value from Edit Text to Number */
}
You can use NumberFormatException :
try {
/* Then parse your value from Edit Text to Number */
} catch(NumberFormatException e) {
/* Any error about formating will catch here */
}

Related

How to check if numeric textbox is empty?

I'm Starting to learn Android Studio java, i'm on basics yet.
Im doing an simple exercice i found on youtube "adding two numbers simple calculator".
I finished it and im trying to improve it by myself but im having trouble, if i let one of the EditTextBox empty the app crash, so i'm trying to check if the EdidTextbox is empty.
I Searched here and tried all thing and none works, or the code give error, or the one it works simple keep crashing. tried using some String to get de value and then check but wont work. (the one it's commented)
Just want a simple check in the editText if its empty just tell me error.
help please. thanks!
Code:
public void OnButtonClick(View ver) {
EditText et1 = findViewById(R.id.et1);
EditText et2 = findViewById(R.id.et2);
TextView tv1 = findViewById(R.id.tv1);
float num1 = Float.parseFloat(et1.getText().toString());
float num2 = Float.parseFloat(et2.getText().toString());
//String input = et1.getText().toString();
//String input2 = et2.getText().toString();
if ( TextUtils.isEmpty(et1.getText().toString()) ) {
et1.setError("Error");
}
else {
et1.setError("Ok");
}
float sum = num1 + num2;
tv1.setText(String.valueOf(sum));
}
}
First implement TextWatcher in your class.
Then use this to check if your textfield is empty or not.
if(et1.getText().toString().lenghth()==0){
et1.setError("This Field cannot be empty");
}
Solution:The below statement will return true
if EditText remains empty
if(TextUtils.isEmpty(et1.getText()){
//enter code here
}
You can use a try catch clause instead of if like this
public void OnButtonClick(View ver) {
EditText et1 = findViewById(R.id.et1);
EditText et2 = findViewById(R.id.et2);
TextView tv1 = findViewById(R.id.tv1);
float num1;
float num2;
try
{
num1 = Float.parseFloat(et1.getText().toString());
num2 = Float.parseFloat(et2.getText().toString());
float sum = num1 + num2;
tv1.setText(String.valueOf(sum));
et1.setError("Ok");
}catch(NullPointerException e){
et1.setError("Error");
}
}
But is just a approach you cant try another different. This catch clause it is only for null point exceptions, but imagine if its something different like division by 0, you can try another clause. Please read this article
So you want to check the editText field is empty or not,you have to check that when user press "add" button.
you do it this way:
if (!etEmail.getText().toString().equals("")) {
//the editbox is not empty
//do what ever you want
} else
etEmail.setError("the edit box is empty");
Update full code:
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!etText.getText().toString().equals("")) {
//do what ever you want
Integer sum = text1 + text2;
} else
etBox.setError(getText(R.string.noEmail));
}
});
}
Thank you for your help, like exe said i used a try catch and it worked, im gonna read the article for some try catch info since im more familiar with if's.
the if didnt work in any way, if there is a if way for this resolution please tell me, i want to try and learn all possible ways to do it.
Thank you.
Working code with try:
public void OnButtonClick(View ver) {
//Atribuir as caixas de texto a varariavel
EditText et1 = findViewById(R.id.et1);
EditText et2 = findViewById(R.id.et2);
TextView tv1 = findViewById(R.id.tv1);
float input1;
float input2;
//Atribui o conteudo das ET para as variaveis e faz/apresenta a soma
try {
input1 = Float.parseFloat(et1.getText().toString());
input2 = Float.parseFloat(et2.getText().toString());
float sum = input1 + input2;
tv1.setText(String.valueOf(sum));
}
catch(NumberFormatException ex) {
//Se estiver vazio msg de erro
Toast.makeText(getApplicationContext(), "Vazio", Toast.LENGTH_SHORT).show();
}
}
}

Input Validation with JOptionPane

I'm doing input validation on a program using JOptionPane boxes. I'm trying to have the input box repeat after the error message every time the user enters in a non-double. How would I do this?
try {
lengthResult = Double.parseDouble(JOptionPane.showInputDialog("What is the length of your garage in square feet?"));
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Please enter a number in digit format.","Inane error",JOptionPane.ERROR_MESSAGE);
}
If you want to repeat the message box until the user enters something valid, I'd go like this:
Double lengthResult = null; //Init to null, which is invalid
String title = "Please anter a number";
int initialType = JOptionPane.QUESTION_MESSAGE;
do {
try {
lengthResult = Double.parseDouble(
JOptionPane.showInputDialog(null,
"What is the length of your garage in square feet?",
title, initialType));
} catch (NumberFormatException e) {
initialType = JOptionPane.ERROR_MESSAGE;
title = "Error: Please enter a number!";
}
} while(lengthResult == null); //Iterate as long as no valid input found
Note that this check relies on lengthResult being an Object of type Double, not a primitive type double. With primitive double you'd need some extra flag as you cannot check on lengthResult value this way.

Convert String to Int with Integer.parseInt don't works

I'm working with JavaEE i need to convert this: request.getParameter("id") to int. The value of request.getParameter("id") is "9" (String).
When I'm trying to convert to int I have
java.lang.NumberFormatException
I've tried java.lang.Integer.parseInt(request.getParameter("id")) and request.getParameter("id",10) but it donsen't works...
Any solutions? Thank you.
A complete full proof code would be
String idString = request.getParameter("id");
if(idString != null) {
try {
System.out.println(idString.trim()); // print to verify
int idInt = Integer.parseInt(idString.trim());
}
catch(NumberFormatException nbe) {
nbe.printStackTrace();
}
}
First you need to check whether String returned by getParameter() is null or not then check whether it is empty ("") String or not then use Integer.parseInt().
String id = request.getParameter("id");
if(null != id && !("".equals(id))) {
try {
int number = Integer.parseInt(id.trim());
}
catch(NumberFormatException e) {
e.printStackTrace();
}
}

How can I make users ONLY input decimal?

So I am very new to java and struggling with my class ... here's what I thought would work:
double costPerKiloHr = 0; //sets value to 0
//tests to make sure a number was inputted
try {
costPerKiloHr = Double.parseDouble(
this.costPerKiloHrText.getText());
}
catch (Exception e) {
JOptionPane.showMessageDialog(this, "Please input a dollar amount including cents",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
You can use regex to check for a match for at least 1 numerical value after the decimal.
String input = scanner.next();
Pattern pattern = Pattern.compile("[0-9]*\\.[0-9]+");
Matcher matcher = pattern.matcher(input);
if(matcher.matches()){
System.out.println("True");
}else{
System.out.println("False");
}
OUTPUT
1.0 True
ASB False
0.25 True
1 False
You cannot make users to input what you want, if you are not a mage or smth. But you can edit the code that accept user input. There can be a huge difference: I don't know what are you using as input. I noticed you're using JOptionPane so I guess you use swing.
In swing there is JTextField and you can control it's content like this:
final JTextField field = new JTextField();
field.addKeyListener(new KeyListener() {
StringBuilder buffer = new StringBuilder();
#Override
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (Character.isDigit(c)) {
buffer.append(c);
}
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
field.setText(buffer.toString());
}
});
If you are using InputStream you should interpret byte pairs as chars and then filter out non-digit values. Declaration of delimiters is required that way.
Assuming you are using Swing (a safe bet given the use of JOptionPane), you can have the user type into a javax.swing.JFormattedTextField... This is an extension of the JTextField widget that takes a Formatter object that defines what is and isn't acceptible. It can be configured (through Formatter.setAllowsInvalid(false)) to never let the user type in an invalid string.
So a formatter for an arbitrary regular expression might look something like this:
public class RegExFormatter extends DefaultFormatter {
protected Matcher matcher;
public RegExFormatter(String regex) {
setOverwriteMode(false);
Pattern p = Pattern.compile(regex);
matcher = p.matcher(""); // initial field contents
}
#Override
public Object stringToValue(String string) throws ParseException {
if (string == null || string.trim().equals(""))
return null;
matcher.reset(string);
if (!matcher.matches()) {
throw new ParseException("Input did not match regex", 0);
}
return super.stringToValue(string); // default returns this string; see docs!
}
}
Then you use this in your code like this:
String regex = "^[1-9]*[0-9](\\.\\d*)?$"; // change this to taste!
RegExFormatter ref = new RegExFormatter(regex);
ref.setAllowsInvalid(false);
JFormattedTextField field1 = new JFormattedTextField(ref);

Empty String validation for Multiple JTextfield

Is there a way to validate a number of JTextfields in java without the if else structure. I have a set of 13 fields, i want an error message when no entry is given for any of the 13 fields and to be able to set focus to that particular textbox. this is to prevent users from entering empty data into database. could someone show me how this can be achieved without the if else structure like below.
if (firstName.equals("")) {
JOptionPane.showMessageDialog(null, "No data entered");
} else if (lastName.equals("")) {
JOptionPane.showMessageDialog(null, "No data entered");
} else if (emailAddress.equals("")) {
JOptionPane.showMessageDialog(null, "No data entered");
} else if (phone.equals("")) {
JOptionPane.showMessageDialog(null, "No data entered");
} else {
//code to enter values into MySql database
the above code come under the actionperformed method a of a submit registration button. despite setting fields in MySQL as NOT NULL, empty string were being accepted from java GUI. why is this? i was hoping perhaps an empty string exception could be thrown from which i could customise a validation message but was unable to do so as empty field were being accepted.
Thanks
Just for fun a little finger twitching demonstrating a re-usable validation setup which does use features available in core Swing.
The collaborators:
InputVerifier which contains the validation logic. Here it's simply checking for empty text in the field in verify. Note that
verify must not have side-effects
shouldYieldFocus is overridden to not restrict focus traversal
it's the same instance for all text fields
a commit action that checks the validity of all children of its parent by explicitly invoking the inputVerifier (if any) and simply does nothing if any is invalid
a mechanism for a very simple though generally available error message taking the label of the input field
Some code snippets
// a reusable, shareable input verifier
InputVerifier iv = new InputVerifier() {
#Override
public boolean verify(JComponent input) {
if (!(input instanceof JTextField)) return true;
return isValidText((JTextField) input);
}
protected boolean isValidText(JTextField field) {
return field.getText() != null &&
!field.getText().trim().isEmpty();
}
/**
* Implemented to unconditionally return true: focus traversal
* should never be restricted.
*/
#Override
public boolean shouldYieldFocus(JComponent input) {
return true;
}
};
// using MigLayout for lazyness ;-)
final JComponent form = new JPanel(new MigLayout("wrap 2", "[align right][]"));
for (int i = 0; i < 5; i++) {
// instantiate the input fields with inputVerifier
JTextField field = new JTextField(20);
field.setInputVerifier(iv);
// set label per field
JLabel label = new JLabel("input " + i);
label.setLabelFor(field);
form.add(label);
form.add(field);
}
Action validateForm = new AbstractAction("Commit") {
#Override
public void actionPerformed(ActionEvent e) {
Component source = (Component) e.getSource();
if (!validateInputs(source.getParent())) {
// some input invalid, do nothing
return;
}
System.out.println("all valid - do stuff");
}
protected boolean validateInputs(Container form) {
for (int i = 0; i < form.getComponentCount(); i++) {
JComponent child = (JComponent) form.getComponent(i);
if (!isValid(child)) {
String text = getLabelText(child);
JOptionPane.showMessageDialog(form, "error at" + text);
child.requestFocusInWindow();
return false;
}
}
return true;
}
/**
* Returns the text of the label which is associated with
* child.
*/
protected String getLabelText(JComponent child) {
JLabel labelFor = (JLabel) child.getClientProperty("labeledBy");
return labelFor != null ? labelFor.getText() : "";
}
private boolean isValid(JComponent child) {
if (child.getInputVerifier() != null) {
return child.getInputVerifier().verify(child);
}
return true;
}
};
// just for fun: MigLayout handles sequence of buttons
// automagically as per OS guidelines
form.add(new JButton("Cancel"), "tag cancel, span, split 2");
form.add(new JButton(validateForm), "tag ok");
There are multiple ways to do this, one is
JTextField[] txtFieldA = new JTextField[13] ;
txtFieldFirstName.setName("First Name") ; //add name for all text fields
txtFieldA[0] = txtFieldFirstName ;
txtFieldA[1] = txtFieldLastName ;
....
// in action event
for(JTextField txtField : txtFieldA) {
if(txtField.getText().equals("") ) {
JOptionPane.showMessageDialog(null, txtField.getName() +" is empty!");
//break it to avoid multiple popups
break;
}
}
Also please take a look at JGoodies Validation that framework helps you validate user input in Swing applications and assists you in reporting validation errors and warnings.
Take an array of these three JTextField, I am giving an overview
JTextField[] fields = new JTextField[13]
field[0] = firstname;
field[1] = lastname; //then add remaining textfields
for(int i = 0; i < fields.size(); ++i) {
if(fields[i].getText().isEmpty())
JOptionPane.showMessageDialog(null, "No data entered");
}
Correct me if i'm wrong, I am not familiar with Swing or awt.HTH :)
Here is one way to do it:
public static boolean areAllNotEmpty(String... texts)
{
for(String s : texts) if(s == null || "".equals(s)) return false;
return true;
}
// ...
if(areAllNotEmpty(firstName, lastName, emailAddress, phone))
{
JOptionPane.showMessageDialog(null, "No data entered");
}

Categories