Android EditText handling String.valueOf(double) always give NaN when input equals " " - android

There are 3 EditText, 1st Price input,2nd Percentage, 3rd Result. I am trying to calculate EditText inputs using onFocusChangeListener.
The Code:
etPercen.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
OnFocusChangedPercenCalculator();
}
}
});
etresult.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
OnFocusChangedResultCalculator();
}
}
});
and
public void OnFocusChangedPercenCalculator() {
String text1 = String.valueOf(etPrice.getNumericValue()).toString();
String text2 = etPercen.getText().toString();
String text3 = String.valueOf(etresult.getNumericValue()).toString();
double input1 = 0;
double input2 = 0;
int i = 0;
if (text1.length() > 0 || text2.length() > 0 || text3.length() > 0)
input1 = Double.parseDouble(text1);
input2 = Double.parseDouble(text2);
if (text1.length() != 0 ){
if(text2.length() != 0) {
double output = (input1 * input2) / 100;
e = String.valueOf(output);
etresult.setText("" + e);
} else if (text2.length() ==0 || text2.matches("")){
etresult.setText(i+"");
}
}else if(text1.length() == 0){
if(text2.length() != 0) {
etresult.setText(i+"");
} else if (text2.length() ==0 || text2.matches("")){
etresult.setText(i+"");
}
}
}
public void OnFocusChangedResultCalculator() {
String text1 = String.valueOf(etPrice.getNumericValue()).toString();
String text2 = etPercen.getText().toString();
String text3 = String.valueOf(etresult.getNumericValue()).toString();
double input1 = 0;
double input3 = 0;
int i = 0;
if (text1.length() > 0 || text2.length() > 0 || text3.length() > 0)
input1 = Double.parseDouble(text1);
input3 = Double.parseDouble(text3);
if (text1.length() != 0 ){
if(text3.length() != 0) {
double output = (input3 / input1) * 100;
e = String.valueOf(output);
etPercen.setText("" + e);
} else if (text3.length() ==0 || text3.matches("")){
etPercen.setText(i);
}
}else if(text1.length() == 0){
if(text3.length() != 0) {
etPercen.setText(i);
} else if (text3.length() ==0 || text3.matches("")){
etPercen.setText(i);
}
}else if (input3 > input1){
etPercen.setText(100);
}
}
What i want to do is 2nd and 3rd EditTexts looking each other. I mean when the user change focus from 2nd/3rd editText then the calculation will begin in an instant. The idea is to make the 2nd one calculate and put the result on the 3rd and make the 3rd one calculate and put the result on 2nd. It depends on the user if he/she wants to change fill/change the value (lets say the price is 10000, the user want to know whats the 20% of it, or the user want the other way around, whats the % of 20000 from 10000). Thats my expectation, but when we emptied the 1st and 3rd edittext the output of the 2nd one will be NaN. How to handle this? i mean avoid the result become NaN?

Ok, I refactored the second method to illustrate what I was talking about. Should be working.
public void OnFocusChangedResultCalculator() {
String text1 = etPrice.getText().toString().trim();
String text2 = etPercen.getText().toString().trim();
String text3 = etresult.getText().toString().trim();
double input1 = text1.length()>0 ? Double.parseDouble(text1) : 0;
double input3 = text3.length()>0 ? Double.parseDouble(text3) : 0;
if (input3 > input1){
etPercen.setText(100);
return;
}
double output = (input3 / input1) * 100;
etPercen.setText(output);
}
UPDATE
public void OnFocusChangedResultCalculator() {
String text1 = String.valueOf(etPrice.getNumericValue()).toString().trim();
String text2 = etPercen.getText().toString().trim();
String text3 = String.valueOf(etresult.getNumericValue()).toString().trim();
double input1 = text1.length()>0 ? Double.parseDouble(text1) : 0;
double input3 = text3.length()>0 ? Double.parseDouble(text3) : 0;
if (input3 > input1){
etPercen.setText(Integer.toString(100));
etresult.setText(Double.toString(input1));
return;
}
double output = (input3 / input1) * 100;
etPercen.setText(Double.toString(output));
}

The NaN error is just Not-a-Number.
I think you need to change your condition
From
if (text1.length() != 0 )
To
if (text1.length() > 0 )
If length is -1 or 1 your if condition will still be satisfied.
By using the operator > instead of != you will be assured that
text1 is not empty.

You are getting NaN because "" and " " are not a number
Instead of using
if (text1.length() != 0 )
use
if(!TextUtils.isEmpty(text1.toString().trim()))
This is an android String utility to perform null and empty check on any String.
Also you probably should to mention in your layout xml that your inputType is number

Related

User Input of int won't be null

I made a code where user put value between some range and my code generate random number for them. Randomization working properly but when fields are blank my app is crash how should I fix it.
randNum.java
Button generateNum = findViewById(R.id.generate_number);
generateNum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
// if(sNum == null || fNum == null){
//
// ans.setText(getString(R.string.enterNumError));
//
// }
// else
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}
});
I try to use null but it is not working.
You need to put validation first on button click. (For checking if user has entered nothing or just spaces in any of edittexts).
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strNum1 = edtl.getText().toString().trim();
strNum2 = edt2.getText().toString().trim();
if (strNum1.length() == 0)
{
showAlert("Please enter Num 1");
}
else if (strNum2.length() == 0)
{
showAlert("Please enter Num 2");
}
else
{
int numvalue1 = Integer.parseInt(strNum1);
int numvalue2 = Integer.parseInt(strNum2);
generateNum (numvalue1, numvalue2); //Call your function for generation of random number here
//do your stuff here
}
}
});
Hope this helps you understand the validation of forms for empty input fields.
P.S: I would recommend you put inputType attribute for your EditTexts if you have not added it already in xml file like:
android:inputType="number"
So you can avoid exception at Integer.parseInt if user enters any alphabet or symbol.
You need to handle NumberFormatException thrown by Integer.valueOf() function
try {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}catch(NumberFormatException e){
Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show();
}

Jump on the word highlighted inside ScrollView

I have here code where it highlights all the words inside the TextView which is equal to the typed string. By pressing the buttons next/previous, It highlights the current word found.
What I'm trying to do is to go to the position of that word currently being highlighted.
I've added this code inside my onClick
myScroll.scrollBy(0, +20);
But it doesn't seem to be what im looking for
Also I've tried something like this
myScroll.scrollTo(0, selected); // getting the index of the highlighted word
// but it's not working
onClickListener to highlight next word
findViewById(R.id.next).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selected++;
String text = ((EditText) findViewById(R.id.editText)).getText().toString();
if(text.equals("") {}
else
selected = changeTextView(details, text, selected);
}
});
method to highlight the text
private int changeTextView(TextView tv, String target, int selected) {
if(selected < 0 ) {
selected = 0;
}
String bString = (String) tv.getText().toString();
int startSpan = 0, endSPan = 0;
Spannable spanRange = new SpannableString(bString);
int currentIndex = 0;
while(true) {
startSpan = bString.indexOf(target, endSpan);
endSpan = startSpan + target.lenght();
boolean isLast = bString.indexOf(target, endSpan) < 0;
if(startSpan < 0)
break;
ParcelableSpan span;
if(currentIndex == selected || isLast && selected > currentIndex) {
span = new BackgroundColorSpan(Color.LTGRAY);
if(isLast && selected > currentIndex) {
selected = currentIndex;
}
} else {
span = new BackgroundColorSpan(Color.YELLOW);
}
currentIndex++;
spanRange.setSpan(
span,
startSpan,
endSpan,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
tv.setText(spanRange);
if(currentIndex == 0) {
return -1;
} else {
return selected;
}
}

How to do fractions in an Android editText. Inputfilter? Custom IME?

I'm trying to write code for an editText which can accept imperial values { ie. 1 , 3/4 , 1 1/3}. So far, with a lot of help from StackOverflow, I have it just about nailed. But there are three things missing.
android:inputType="number" or numberSigned, numberDecimal, phone etc
none of these display the / key I need to enter data and the QWERTY keyboard is too cumbersome for a single keypress. I'm amazed there isn't a keyboard for this, what do the yanks do? Can I override and replace a single key on the stock keyboard, do I have to implement my own keyboard for this seemingly simple task?
I am also struggling with the logic which prevents the first character being a space or /. I can allow one of each in a given string no problem, I just can't prevent it being the first key. Additionally, when you enter a value - like "1 5/9" - if you backspace to the /, the flags are not reset, so you are prohibited from entering another /.
Code for the InputFilter is as follows:
imperial_filter = new InputFilter() {
boolean canEnterSpace = true, canEnterSlash = true;
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (imperial_editText.getText().toString().equals("")) {
canEnterSpace = true;
canEnterSlash = true;
}
StringBuilder builder = new StringBuilder();
for (int i = start; i < end; i++) {
char currentChar = source.charAt(i);
if (Character.isDigit(currentChar) || (Character.isWhitespace(currentChar) && canEnterSpace && canEnterSlash) || (currentChar == '/' && canEnterSlash)) {
builder.append(currentChar);
if (Character.isWhitespace(currentChar)) canEnterSpace = false;
if (currentChar == '/') canEnterSlash = false;
}
}
return builder.toString();
}
};
And this one is a little more complex, slightly adapted from code already on StackOverflow:
public float testImperialString(String testString) {
boolean goodInput = true, goodInputSpace = true, containsSpace = false;
float result = 0, whole = 0;
String fractions = "";
if (testString.contains(" ")) {
containsSpace = true;
String pieces[] = testString.split(" ");
try {
whole = Float.parseFloat(pieces[0]);
fractions = pieces[1];
} catch (Exception e) {
goodInputSpace = false;
}
} else fractions = testString;
if (fractions.contains("/")) {
//possible division
String pieces[] = fractions.split("/");
if (pieces.length != 2) {
goodInput = false;
} else {
try {
float numerator = Float.parseFloat(pieces[0]);
float denominator = Float.parseFloat(pieces[1]);
result = numerator / denominator;
} catch (Exception e) {
goodInput = false;
}
}
}
if (!testString.contains(" ") && !(result > 0)) {
try {
result = Float.parseFloat(testString);
} catch (Exception e) {
goodInput = false;
}
}
Log.d(TAG, "Contains Space = " + containsSpace + " Good Input = " + goodInput + " Good InputSpace = " + goodInputSpace);
return whole + result;
}
I run that result through a method which converts imperial measurements into a metric equivalent, that I can perform maths functions with.
TL:DR
I need a number keyboard with a / symbol
I need to prevent a space or / as the first letter of an input
I need to re-allow a space or / input, if a previous occurrence in a string was deleted.

LUHN credit-card validation fails on a valid card number

In my application i want to check whether the user have entered valid card number for that i have used LUHN algorithm.I have created it as method and called in the mainactivity. But even if i give valid card number it shows invalid.While entering card number i have given spaces in between i didn't know because of that its not validating properly. Please help me in finding the mistake.
CreditcardValidation.java
public class CreditcardValidation {
String creditcard_validation,msg;
//String mobilepattern;
public static boolean isValid(long number) {
int total = sumOfDoubleEvenPlace(number) + sumOfOddPlace(number);
if ((total % 10 == 0) && (prefixMatched(number, 1) == true) && (getSize(number)>=16 ) && (getSize(number)<=19 )) {
return true;
} else {
return false;
}
}
public static int getDigit(int number) {
if (number <= 9) {
return number;
} else {
int firstDigit = number % 10;
int secondDigit = (int) (number / 10);
return firstDigit + secondDigit;
}
}
public static int sumOfOddPlace(long number) {
int result = 0;
while (number > 0) {
result += (int) (number % 10);
number = number / 100;
}
return result;
}
public static int sumOfDoubleEvenPlace(long number) {
int result = 0;
long temp = 0;
while (number > 0) {
temp = number % 100;
result += getDigit((int) (temp / 10) * 2);
number = number / 100;
}
return result;
}
public static boolean prefixMatched(long number, int d) {
if ((getPrefix(number, d) == 5)
|| (getPrefix(number, d) == 4)
|| (getPrefix(number, d) == 3)) {
if (getPrefix(number, d) == 4) {
System.out.println("\nVisa Card ");
} else if (getPrefix(number, d) == 5) {
System.out.println("\nMaster Card ");
} else if (getPrefix(number, d) == 3) {
System.out.println("\nAmerican Express Card ");
}
return true;
} else {
return false;
}
}
public static int getSize(long d) {
int count = 0;
while (d > 0) {
d = d / 10;
count++;
}
return count;
}
public static long getPrefix(long number, int k) {
if (getSize(number) < k) {
return number;
} else {
int size = (int) getSize(number);
for (int i = 0; i < (size - k); i++) {
number = number / 10;
}
return number;
}
}
public String creditcardvalidation(String creditcard)
{
Scanner sc = new Scanner(System.in);
this.creditcard_validation= creditcard;
long input = 0;
input = sc.nextLong();
//long input = sc.nextLong();
if (isValid(input) == true) {
Log.d("Please fill all the column","valid");
msg="Valid card number";
}
else{
Log.d("Please fill all the column","invalid");
msg="Please enter the valid card number";
}
return msg;
}
}
MainActivity.java
addcard.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
if(v.getId()==R.id.btn_add)
{
creditcard= card_number.getText().toString();
cv = new CreditcardValidation();
String mob = cv.creditcardvalidation(creditcard);
Toast.makeText(getActivity(), mob, 1000).show();``
refer code below
EditText cardNumber=(EditText)findViewById(R.id.cardNumber);
String CreditCardType = "Unknown";
/// Remove all spaces and dashes from the passed string
String CardNo ="9292304336";///////cardNumber.getText().toString();
CardNo = CardNo.replace(" ", "");//removing empty space
CardNo = CardNo.replace("-", "");//removing '-'
twoDigit=Integer.parseInt(CardNo.substring(0, 2));
System.out.println("----------twoDigit--"+twoDigit);
fourDigit=Integer.parseInt(CardNo.substring(0, 4));
System.out.println("----------fourDigit--"+fourDigit);
oneDigit=Integer.parseInt(Character.toString(CardNo.charAt(0)));
System.out.println("----------oneDigit--"+oneDigit);
boolean cardValidation=false;
// 'Check that the minimum length of the string isn't <14 characters and -is- numeric
if(CardNo.length()>=14)
{
cardValidation=cardValidationMethod(CardNo);
}
boolean cardValidationMethod(String CardNo)
{
//'Check the first two digits first,for AmericanExpress
if(CardNo.length()==15 && (twoDigit==34 || twoDigit==37))
return true;
else
//'Check the first two digits first,for MasterCard
if(CardNo.length()==16 && twoDigit>=51 && twoDigit<=55)
return true;
else
//'None of the above - so check the 'first four digits collectively
if(CardNo.length()==16 && fourDigit==6011)//for DiscoverCard
return true;
else
if(CardNo.length()==16 || CardNo.length()==13 && oneDigit==4)//for VISA
return true;
else
return false;
}
also u can refer this demo project
Scanner.nextLong() will stop reading as spaces (or other non-digit characters) are encountered.
For instance, if the input is 1234 567 .. then nextLong() will only read 1234.
However, while spaces in the credit-card will [likely] cause it to fail LUHN validation with the above code, I make no guarantee that removing the spaces would make it pass - I'd use a more robust (and well-tested) implementation from the start. There is no need to rewrite such code.

Android: If/Else statement makes app crash

I'm trying to tell if an android int is null by using If/Else
public void onClick(View v) {
EditText min = (EditText) findViewById(R.id.EditText01);
EditText max = (EditText) findViewById(R.id.maxnum);
EditText res = (EditText) findViewById(R.id.res);
int myMin = Integer.parseInt(min.getText().toString());
int myMax = Integer.parseInt(max.getText().toString());
String minString = String.valueOf(myMin);
String maxString = String.valueOf(myMax);
int f = (int) ((Math.random()*(myMax-myMin+1))+myMin);
if (minString.equals(""))
{
// Do Nothing
}
if (maxString.equals(""))
{
// Do Nothing
}
res.setText(String.valueOf(f));
There are no any errors, but when I'm running the app its crashing when im pressing the button.
I'm also trying to use null instead of "":
if (minString.equals(null))
{
// Do Nothing
}
if (maxString.equals(null))
{
// Do Nothing
}
And i have a crash.
Please help me!!!
public boolean equals (Object object)
Compares the specified object to this string and returns true if they are equal. The object must be an instance of string with the same characters in the same order.
So its returning error so if you want to check if its null then use == operator on the object.
if (maxString == null )
Use
int myMin = 0;
int myMax = 0;
if(min.getText().toString()!="")
myMin = Integer.parseInt(min.getText().toString());
if(max.getText().toString()!="")
myMax = Integer.parseInt(max.getText().toString());
String minString = String.valueOf(myMin);
String maxString = String.valueOf(myMax);
int f = (int) ((Math.random()*(myMax-myMin+1))+myMin);
if (minString.equals(""))
{
// Do Nothing
}
if (maxString.equals(""))
{
// Do Nothing
}
do if (maxString == null )
{
// do something
}
int variables can't be null
If a null is to be converted to int, then it is the converter which decides whether to set 0, throw exception, or set another value (like Integer.MIN_VALUE)
So if you convert int to string again you cannot get null value.
check = input.getText().toString();
try {
if (!check.equals("null")) {
int max = Integer.parseInt(input.getText().toString());
int constant1 = 1;
int constant2 = 1;
int nextNumber = 0;
int count = 0;
String fibResult = "";
for (int i = 0; i <= max; i++) {
fibResult += "F" + count + "=" + nextNumber + "\n";
constant1 = constant2;
constant2 = nextNumber;
nextNumber = constant1 + constant2;
count++;
}
dspResults.setText("\n" + fibResult);
} else {
dspResults.setVisibility(View.VISIBLE);
dspResults.setText("Invalid");
dspResults.setText(Gravity.CENTER);
dspResults.setTextColor(Color.DKGRAY);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
public void onClick(View v) {
EditText min = (EditText) findViewById(R.id.EditText01);
EditText max = (EditText) findViewById(R.id.maxnum);
EditText res = (EditText) findViewById(R.id.res);
int myMin = Integer.parseInt(min.getText().toString());
int myMax = Integer.parseInt(max.getText().toString());
String minString = String.valueOf(myMin);
String maxString = String.valueOf(myMax);
int f = (int) ((Math.random()*(myMax-myMin+1))+myMin);
{
if (minString.equals(""))
{
// Do Nothing
res.setText(String.valueOf(f));
return false;
}
else if (maxString.equals(""))
{
// Do Nothing
res.setText(String.valueOf(f));
return false;
}
else
res.setText(String.valueOf(f));
return true ;
}

Categories

Resources