Determine if content in editText is a "." ONLY - android

I have written a calculator type app. My mates found that entering single decimal points only into the editText's makes the app crash. Decimal numbers and integers work fine, but I get a number format exception when .'s are entered.
I want to check if a single . has been placed in an editText, in order for me to display a toast telling the user to stop trying to crash the app.
My issue is that a . doesn't have a numerical value...

You can wrap it in a try/catch which should be done anyway when parsing text. So something like
try
{
int someInt = Integer.parseInt(et.getText().toString());
// other code
}
catch (NumberFormatException e)
{
// notify user with Toast, alert, etc...
}
This way it will protect against any number format exception and will make the code more reusable later on.

You can treat .1 as 0.1 by the following.
String text = et.getText().toString();
int len = text.length();
// Do noting if edit text just contains a "." without numbers
if(len==0 || (len==1 && text.charAt(0).equals(".")))
return;
if(text.charAt(0).equals(".") && text.length() > 1) {
text = "0" + text;
}
// Do your parsing and calculations

Related

GetText compare

So i have a EditText field, which i want to, check if the age is above and under my limits.
if (Integer.parseInt(age.getText().toString()) < 18 && Integer.parseInt(age.getText().toString()) >= 0)
But also, i want to simply check if the field is empty, for what i used.
else if (age.getText().toString().isEmpty())
Unluckly this one is not working, i think it sort of get in to conflict with the first one or something, because i tried with just one condition of both, and it works..
I also tried to store in String variable the method to check isEmpty(), and also in int one, to do the age comparation, but it still not working.
Thanks in advance.
The code should be:
if (age.getText().toString().trim().isEmpty()){
//The EditText field is empty
}else{
try{
if (Integer.parseInt(age.getText().toString().trim()) < 18 && Integer.parseInt(age.getText().toString().trim()) >= 0){
//Your code here
}else{
//Input value is over 18 or under 0
}
}catch(Exception ex){
//There was an error parsing the input (if your user writes letters, parseInt fails)
}
}

Getting Int from EditText causes error?

So first of all sorry if this has already been asked and answered before, I couldn't find anything relating to my issue.
So I'm working on a project for college and I need to get int values from EditText widgets. I was told to use parseInt to do this however when running my program, that line of code causes the application to crash. I don't know what I'm doing wrong, I'm still very new to android development, thanks for the help :)
public void Calculate (View view)
{
int MilesTravelled;
int FuelUsed;
int MPG;
/* the two lines below are what cause the application to crash */
MilesTravelled = Integer.parseInt(txtMilesTravelled.getText().toString());
FuelUsed = Integer.parseInt(txtFuelUsed.getText().toString());
FuelUsed = (int) (FuelUsed / 4.55);
MPG = MilesTravelled / FuelUsed;
lblMPG.setText(FuelUsed);
}
Do you have this in the onCreate() function?
EditText txtMilesTravelled = (EditText) findViewById(R.id.YourEditText);
But I think you mixed Integer and int. They are not the same:
See this link!
First of all, don't capitalize the first letter of an variables or method names. Following the Java coding conventions, only do that for classes.
What is probably causing your app to crash is you trying to set the text of a label to an integer. The setText method for a TextView needs to take in a string.
So change:
lblMPG.setText(FuelUsed);
to:
lblMPG.setText(String.valueOf(FuelUsed));
Otherwise it might be that it's trying to parse a non-numerical string to an integer.
For exmaple, if the EditText is blank, it will cause your app to crash. To prevent that, try this:
int MilesTravelled = 0, FuelUsed = 0;
try {
MilesTravelled = Integer.parseInt(txtMilesTravelled.getText().toString());
FuelUsed = Integer.parseInt(txtFuelUsed.getText().toString());
} catch (NumberFormatException nfe) {
Toast.makeText(getApplicationContext(), "Error NFE!", 0).show();
nfe.printStackTrace();
}
This way, it will catch a NumberFormatException error (parsing a string to an integer that can't be represented as an integer, such as "hello"). If it catches the error, it will toast that an error has occurred and your integer variables will remain 0.
Or you could just test if the strings contain only digits using the following regex:
int MilesTravelled = 0, FuelUsed = 0;
if (txtMilesTravelled.getText().toString().matches("[0-9]+")) {
MilesTravelled = Integer.parseInt(txtMilesTravelled.getText().toString());
} else {
// contains characters that are not digits
}
if (txtFuelUsed.getText().toString().matches("[0-9]+")) {
FuelUsed = Integer.parseInt(txtFuelUsed.getText().toString());
} else {
// contains characters that are not digits
}
If that's not the problem, then make sure you define your variables properly.
txtMilesTravelled and txtFuelUsed should be EditText:
EditText txtMilesTravelled = (EditText)findViewById(R.id.txtMilesTravelled);
EditText txtFuelUsed = (EditText)findViewById(R.id.txtFuelUsed);
And make sure that your R.id.editText actually exists on your layout and that the IDs are the correct ones.
Last thing, make sure FuelUsed is not 0 before calculating MPG because then you are dividing by 0:
int MPG = 0;
if (FuelUsed != 0) {
MPG = MilesTravelled / FuelUsed;
}
I am assuming that you're entering perfect integers in the EditTexts. It might be a good idea to use the trim function txtMilesTravelled.getText().toString().trim() before using parseInt.
However, I think the major problem is here : lblMPG.setText(FuelUsed);
FuelUsed is an integral value, when you pass an integer to setText(), it looks for a string resource with that integral value. So you should be passing a String to the setText() method.
Use : lblMPG.setText(Integer.toString(FuelUsed));

android : app crash if user inputs two decimal points like "1..5" instead of "1.5"

i have an android program where i have successfully restricted the user to input only value after decimal.. the problem is if user inputs two decimal points like "1.." then the app crashes. i have allowed only one special character to be used i.e decimal point itself. so how can i restrict the user from entering two decimal points or else show some validation.
i need something like this
else if(txtLdays.getText().toString().trim().equals(".."))
{
txtLdays.requestFocus();
txtLdays.setError("Double decimal ?");
return false;
}
Try this..
Use contains like below
else if(txtLdays.getText().toString().trim().contains(".."))
{
txtLdays.requestFocus();
txtLdays.setError("Double decimal ?");
return false;
}
EDIT
String to double
double result = Double.parseDouble(txtLdays.getText().toString().trim());
int to double
double result = (double) 12;
If user enters 12.
then check endsWith
double result;
if(txtLdays.getText().toString().trim().endsWith("."))
result = Double.parseDouble(txtLdays.getText().toString().trim().replace("\\.", ""))
There are two possibilitites
if you want to restrict when any button pressed..
then replace all ".." characters with empty chars like..
String data=View.getText().toString().replaceAll("..", "");
2.if you restrict when the user is typing then write a TextWatcher listener for the Edittext and you need to peform some validations there...
Did you tried setting decimal input type ?
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal|number"
/>
Try this :
int count = StringUtils.countOccurrencesOf((txtLdays, ".");
if (count > 1){
txtLdays.requestFocus();
txtLdays.setError("Double decimal ?");
}
Please downlaod this jar file Commons Lang
The right way would be to match the value against a regular expression.
Here is an example that allows a string that starts/end with zero or more spaces and contains a double decimal point number:
//First make sure you avoid null pointer exception
if (txtLdays != null && txtLdays.getText() != null) {
String daysString = txtLdays.getText().toString();
String regex = "^\s*\d+\.\.\d+\s*$"
if (daysString.matches(regex)) {
txtLdays.requestFocus();
txtLdays.setError("Double decimal ?");
return false;
}
}
You can youse some kind of online regular expression tool to verify your matcher.
equals will check Object.
You need to check equalsIngnoreCase(); this ll check all the character
specially u need
else if(txtLdays.getText().toString().trim().indexOf("..") != -1 ){
txtLdays.requestFocus();
txtLdays.setError("Double decimal ?");
return false;
}

HTML Formatted String inserting into TextViews and EditText

All,
I have a database that will store an HTML tagged text to retain formatting information from an EditText. I create this string using HTML.toHtml(EditText.getText). I notice this method wraps whatever Spanned Text is put in it with <p> and </p>. The issue with that is when I got to use the method HTML.fromHtml(HTMLFormattedString) and then use the setText method of either a TextView or EditText there are two extra lines at the end of my actual text, which makes sense because that is how the paragraph tag works with HTML.
My question is is there anyway to make the textView or EditText shrink to not display the extra blank lines? What is the simplest way to do this? I have experimented with just removing the last <p> and </p>, but that only works if the user did not enter 3 or more new lines with the return key.
I ended up searching for white space at the end of the spanned text that was created and removed it. This took care of extra spaces due to the <p> </p> and was less time consuming than overriding the mentioned class to achieve the same results.
public SpannableStringBuilder trimTrailingWhitespace(
SpannableStringBuilder spannableString) {
if (spannableString == null)
return new SpannableStringBuilder("");
int i = spannableString.length();
// loop back to the first non-whitespace character
while (--i >= 0 && Character.isWhitespace(spannableString.charAt(i))) {
}
return new SpannableStringBuilder(spannableString.subSequence(0, i + 1));
}
Well this is just a round about approach. I had the same issue. And you are provided with two options,
1)As you said that paragraph tag works the way what you have suspected. What it does , it appends two "\n" values to the end of each <\p> tag. So you can convert the html to string and remove the last two characters which are usually two "\n"s
or
2) You have get into the Html Class itself. That is, you have to override the HTML class and look for handleP(SpannableStringBuilder text) and change its core logic a little bit.
private static void handleP(SpannableStringBuilder text) {
int len = text.length();
if (len >= 1 && text.charAt(len - 1) == '\n') {
if (len >= 2 && text.charAt(len - 2) == '\n') {
return;
}
text.append("\n");
return;
}
if (len != 0) {
text.append("\n\n");
}
}
As you can see here, it appends two "\n" in len!=0 which is were you have to do the change.

Why is my Android app force closing when I try to check if an EditText has a double

Scanner scanner = new Scanner(lapsPerMile_st);
if (!scanner.hasNextDouble()) {
Context context = getApplicationContext();
String msg = "Please Enter Digits and Decmials Only";
int duration = Toast.LENGTH_LONG;
Toast.makeText(context, msg, duration).show();
lapsPerMileEditText.setText("");
return;
} else {
//Edit box has only digits, Set data and display stats
data.setLapsPerMile(Integer.parseInt(lapsPerMile_st));
lapsRunLabel.setVisibility(0);
lapsRunTextView.setText(Integer.toString(data.getLapsRun()));
milesRunLabel.setVisibility(0);
milesRunTextView.setText(Double.toString(data.getLapsRun()/data.getLapsPerMile()));
}
<EditText
android:id="#+id/mileCount"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginTop="110dp"
android:inputType="numberDecimal"
android:maxLength="4"
/>
For some reason if I enter a non decimal number such as 3, or 5, it works fine but when I enter a floating point such as 3.4 or 5.8 it force closes. I cant seem to figure out whats going on. Any ideas?
Use the right type: Integer.parseInt, Float.ParseFloat, ... and take in account that you are using Java so if one ouf the parse's fails you'll get an exception: NumberFormatException.
String int_string = "1";
int data = 0; // 0 as default value
try
{
data = Integer.parseInt (int_string);
}
catch (NumberFormatException e)
{
// You are trying to parse and int from a string that is not an int!
}
The culprit is almost certainly parseInt. Go ahead and connect to your device using the adb (adb logcat -v time) to view the log, as well as the stack trace generated when your app crashes.
ParseInt doesn't like any non-integer characters (I.E. It's bombing when it hits the decimal point).
I recommend using try-catch to surround your parseInt or Parse"Anything" methods.
Next, you may want to restrict the allowable characters to integer-type only within your layout XML:
https://developer.android.com/reference/android/widget/TextView.html#attr_android:numeric

Categories

Resources