read ViewText convert to double - android

My app has a number of numeric user input fields which need sanity checks before proceeding to the next intent.
I read viewText fields, convert them to double and then do the (numeric) tests but odd things happen and I find that while the code runs on my HTC in debug, it falls over if I publish then download the published version. My code is sumarised as;
String sFy;
double mFy=0;D
sFy=(txtFy.getText().toString());
mFy=Double.parseDouble(sFy);
if sFy is null the .parsedouble crashes. If I use;
sFy=(txtFy.getText().toString());
mFy=getDouble(sFy);
private double getDouble(String string){
double temp=0.0;
try {
temp = Double.parseDouble(string.trim());
} catch(NumberFormatException nfe) {
System.out.println("getDouble, Could not parse " + nfe);
}
return temp;
}
it works, even if sFy is empty.
Can anyone tell my why, or suggest a 'correct' method?

Maybe like that :
String sFy;
double mFy=0;
sFy = txtFy.getText();
if ((sFy != ""){
mFy=Double.parseDouble(sFy);
}
Or maybe I haven't really understood your problem...

Your getDouble is returning 0.0 in case there is NumberFormatException.
Do you see debugger coming to System.out.println("getDouble, Could not parse " + nfe);

Related

Android slpit string doubleparse and pass it to a method that converts degrres to decimal

I have a android method that converts degrees minutes and seconds to decimal. I am getting the text from edittext split it and convert it to double array before I pass it to the method. Then I wanted to get the double returned in a decimal form to be displayed in the original edittext as string. Here is the code,
public double DegreeToDecimal(double d, double m, double s)
{
double decimal;
decimal = d + m/60 + s/3600;
return decimal;
}
try
{
String string = dtod.getText().toString();
String[] s = string.split(":");
String decimal;
double d = DegreeToDecimal(Double.parseDouble(s[0]), Double.parseDouble(s[1]), Double.parseDouble(s[2]));
decimal = String.valueOf(d);
dtod.setText(decimal);
}catch (Exception e){
e.printStackTrace();
}
When I do this on a button click, nothing happens. The Logcat doesn't show anything and the code is simply ignored. What am I doing wrong?
Thanks for the help.
Your code formatting is all over the place and hard to read, please try to use correct indentation next time!
From the code you posted it's hard to tell what happens. If Logcat doesn't show any stacktraces like you said, and if your code is "ignored" as you say then my guess is that it doesn't get called.
Did you attach an OnClickListener to that button?
Otherwise try to log something between your lines or use a debugger to find out what really happens!

Get EditTextValue and parse it into a decimal with only one digit for integer part

I'm having an issue when I get a whole number from an EditText and try to change that to a decimal so I can use it for calculations. Could someone explain how to do this?
For Example. if someone was to enter 120 into the EditText and I got the integer from it, how would I then change that integer of 120 into 1.20 and continue calculations with it?
Thanks!!
EditText myEditText = (EditText)findViewById(R.id.YOUR_EDIT_TEXT_ID);
String numberAsString = myEditText.getText().toString();
double myDecimal;
try {
myDecimal = Double.parseDouble(numberAsString);
if (myDecimal >= 10)
{
int digits = 1 + (int)Math.floor(Math.log10(myDecimal));
myDecimal = myDecimal / ((Math.pow((double)10, ((double)digits) - 1)));
System.out.println(myDecimal);
}
} catch (NumberFormatException e) {
//handle exeption
e.printStackTrace();
}
You need to get the contents from your EditText as a string, and from there you can parse it into an integer. This is done like so:
int wholeNum = Integer.parseInt(yourEditText.getText().toString());
int three = Integer.parse("3");
I know you can use this to parse a string into an integer, there is probably a parse method in double aswell!
Check this also :
Convert a String to Double - Java
+1 to anthony for answering 1 minute before me haha

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;
}

Determine if content in editText is a "." ONLY

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

Program seems to be ignoring lines of code

I need help with this function.
I know that the if statement recognizes my input because it affects the program elsewhere, but I'm not sure what's going on because this particular Log doesn't display anything even in adb logcat.
Other Log statements in the same class file that this function is from display just fine, and the value update does seem to be changing ("show all" blanks it for some reason but I can figure that out after I get the log to work.)
I am unsure how to search for this problem because it is very specific and I have no idea what causes it (probably something simple that I didn't think of, though.)
void command(String input)
{
//do stuff here
//update = whatever
if(input.equalsIgnoreCase("show all"))
{
update=printAllRooms();
Log.i(input, update);
}
else update=input; //just for testing, will delete later
}
the printAllRooms function:
public String printAllRooms() //for debug purposes
{
String result = "";
for (Iterator<Room> iterator = rooms.iterator(); iterator.hasNext();) {
Room current = iterator.next();
result = result + current.toString()+"\n";
Log.i("printallrooms", current.toString());
}
return result;
}
A note on using Log.
The first argument sent to Log is typically a fixed string indicating the name of the class you are in.
So at the top of your class you might define:
private static final String TAG = "MyClassName";
Then you would use TAG for your log statements in that class.
Log.i(TAG, "My input was: " + input + " Update was: " + update;
To put it mildly, your function looks quite odd. Set a breakpoint at your Log statement, run the debugger and then inspect the variable value contained in update. Most likely, printAllRooms() is not doing what you think.
If the iterator doesn't work for you, try using the For-Each loop:
for (Room r : rooms) {
result = result + r.toString()+"\n";
Log.i("printallrooms", r.toString());
}

Categories

Resources