Checking for input with space - android

I've made an offline currency convertor that gets the users input in the EditText section using a TextWatcher and returns the required ouptut from methods...and I"ve made it an a way that the user cannot insert a "null" value in the EditText section and then press the convert button by using euro.getText !==null for example.But I don't know how to proceed when the user leaves some space between the input,for instance 29 50.This will make my program to crash.My question what should I use to check for an input with space in order to avoid a program crash?Thank you.

Your program crashes with number format exception. You can do so:
try{
double value = Double.parseDouble(editText.getText().toString());
} catch(NumberFormatException ex){
Log.e(TAG, "improper number format");
//show some dialog saying what's the format that should be entered
}
You can also go with a regex:
String editTextValue = editText.getText().toString();
if(editTextValue.matches("\\d+\\.\\d+")){
double value = Double.parseDouble(editTextValue);
} else{
//show dialog saying what should be the format.
}

This is actually quite easy.
Does your app accept numbers with a comma or a dot? Either way, you can simply replace the String by the symbol of you choice by using the following:
String unspaced = edittext.getText().toString().replace(' ', '.'); // or , depending on what your app uses

Related

Sum values ​only if they exist

Hello everyone, I have a problem adding the values ​​of edittexts, I
created 20 fields but I want to add only the ones I enter the values,
example: field 1 = value 100 field 2 = value 50 field 3 = value 0
field 4 = value 0 result = 150 how can i perform this? I used
Double.parseDouble taking the value of edittext, tried to use the if
else method and was unsuccessful ... The goal of my app is to create
a table with items and values, and then turn it into PDF, thanks
everyone!
If I do not enter the value in any of the fields, a message appears
toast message saying String is empty.
I do not clearly get what scenario u have but it seems like you are getting input from some text fields and want to add those text fields values then u can try that
Optional<String> value= Optional.ofNullable(textFieldValue)
.filter(s -> !s.isEmpty()&& s.matches("-?\\d+(\\.\\d+)?");
if(value.isPresent()){
double d = Double.parseDouble(value.get());
//then do your addition stuff
}

Android, Xamarin, EditTexts: Disable the user from deleting the first letters

I want the user to type in his or her Facebook account-link (don't have a better solution atm).
Now, when the user clicks the edittext it is supposed to say : "www.facebook.com/". Now the cursor is supposed to be at the END of the edittext (after the "/") and the user is not supposed to delete the first letters so that the "www.facebook.com/" stays exactly where it is. This will have the user to ONLY type in his or her facebook name and therefore connect the profile.
Is there a way of doing this?
Thank you :)
You can do that by using the event "TextChanged" and in your code validate if the size is big than your string, like that:
if (((EditText)sender).Text.Length >= 17)
{
((EditText)sender).Text = e.NewTextValue;
}
else
{
((EditText)sender).Text = "www.facebook.com/";
}
So if the value is bigger than your string you will replace that for the value, if not you just set the value with your string

Number Format Exception "Invalid Double"

I have to build a calculator and i am making some validations, the code is kinda long so i will only put the part that is breaking it.
It is a validation that makes the multiplication, it breaks when trying to multiply a negative number, every other operation is done correctly but the multiplication:
else if(resulttxt.getText().toString().contains("*")){
String resultarray=resulttxt.getText().toString();
String[] split=resultarray.split("\\*");
finalresult = Double.valueOf(split[0]) * Double.valueOf(split[1]);
if (finalresult<0){
negative=true;
}else{
negative=false;
}
resulttxt.setText(String.valueOf(finalresult));
resulttxt is received from a TextView that gets it's data from cliking on the numbers or the signs which are also TextViews (not buttons but they do have the On click listener)the operation is done when ciclking on the = sign.
This throws an error if for example i try to do -6*45:
java.lang.NumberFormatException: Invalid double: "6*45"
Like i said everything works with the addition,substraction and division it is only the multiplication that breaks.
I tried executing your code in the compiler :
String resulttxt = "-6*45";
boolean negative = false;
if(resulttxt.contains("*")){
String resultarray=resulttxt;
String[] split=resultarray.split("\\*");
double finalresult = Double.valueOf(split[0]) * Double.valueOf(split[1]);
if (finalresult<0){
negative=true;
}else{
negative=false;
}
System.out.println(finalresult);
}
Every thing worked fine for, please verify datatype used in your program.
addition, multiplication and division works fine. "-6+45, -6*45 and -6/45"(any other combination. I just used the same)
However for subtraction as the pattern is "-6-45" the above logic will fail and throw number format exception. This is because if you split "\-", the "-" is first character in string and there is nothing before it.
Thus your split will fail. So to avoid this you can always take last index of character to split using substring function.
OMG dudes... this is what was the problem:
I had this validation at the end of the other operations, so BEFORE even going to the multiplication part it entered the "-" validation when it checks
if(resulttxt.contains("-")){
because it is a negative value so it does have a "-"... so it entered as a substraction instead as a multiplication because of that...
To solve it i had to put the substraction validation at the bottom of all of them.
So thank you for the guys who suggested me to check the line where the error was thrown i wouldn't have known logcat actually tells you were the mistake is and to my surprise it was on the substraction validation which to me was a "WTF" moment and then i realized what i just told you.
Try this instead :
String s1 = resultarray.substring(0,resultarray.indexOf("*"));
String s2 = resultarray.substring(resultarray.indexOf("*")+1,resultarray.length());
double d1= Double.valueOf(s1);
double d2= Double.valueOf(s2);
Hope this helps

Android NumberFormatException error with a simple number input from EditText

So I have a simple Edit-text with number input.
User enters his phone number and it is saved into DB obviously that is the goal.
now every time i do
int contactNumber=Integer.parseInt(mContactNumber.getText().toString());
I get an error thrown saying NumberFormatException for some reason it doesn't like a string of number. I have made sure that mContactNumber field in the android input field has the
android:input="number"
now i also tried just to be sure
int contactNumber=Integer.parseInt(mContactNumber.getText().toString().trim());
still the same error
Guys any ideas?
Try putting the Type to ' long ' instead of ' int '. Hope that will work for you.
This might be because you are leaving the text field empty. Are you sure you are not parsing an empty string?
You need to put a simple condition:
if(mContactNumber.getText().length()>0)
{
int contactNumber=Integer.parseInt(mContactNumber.getText().toString().trim());
}
For phone Number you can not take it as Integer. try to take it as string only and after getting that string you can do the check for the numbers only by
TextUtils.isDigitsOnly(str);

EditBoxPreference() storing the value as an int instead a string

I'm writing an Android application that can easily back up files and folders to the users PC. One of the things I wanted to implement was allowing the client running on the Android device to change the port I will be sending the file to.
For this, I've created an EditTextPreference to store the value.
The code I'm using to get this value back is
port = prefs.getString("serverPort", "<unset>");
However, this returns a string and I need an int, so I tried to use
sendPort = Integer.parseInt(port);
But this crashes the Android application, with (I think) a number format exception.
Is there anyway I can explicitly store the value that is entered as an Integer to make it easier?
I tried to use the method
port = prefs.getInt(...);
but that didn't work either.
Thanks for any help.
This will take whatever is entered into your edit text and put it in an int.
int yourValue = Integer.valueOf(editText.getText().toString());
Note that Integer.valueOf() will return a format exception if you put a String in it that doesn't have an integer value.
You can then use
prefsEdit.putInt("serverPort", yourValue);
prefsEdit.commit();
to save it to preferences. And this to retrieve it
int port = prefs.getInt("serverPort", -1);
Saving the port as String or int doesn't make a big difference. Either way you'll have to convert it.
Your app crashes, because it cannot convert <unset> to a number, that's where the NumberFormatException comes from.
Solution:
Catch the NumberFormatException and set sendPort to a default value.
port = prefs.getString("serverPort", "<unset>");
try {
sendPort = Integer.parseInt(port);
} catch (NumberFormatException ex) {
sendPort = 1234;
}

Categories

Resources