String from EditText to float - java

I have an EditText for which will be using for a float number. So I'm trying to read the text from the EditText and put it into a float variable. But I seem to have a text to float problem. This is the line I have:
float Number = ( ( EditText )findViewById( R.id.edit_float ) ).getText();
I've tried using Float.parseFloat(string) and just general casting, but nothing seem to do it. What can I do here? Also, is there a way to check for a valid float number before writing it to a variable?

Try this.
EditText edt = (EditText) findViewById(R.id.edit_float);
float number = Float.valueOf(edt.getText().toString());
You use the valueOf() method if the Float wrapper class to convert a string to a float. IN this example I get the Editable object of that EditText with getText() on which I call the toString() method to obtain a string from it.
Update: Totally right guys sorry. Time to increment my sheep counter.

float getFloatFrom(EditText txt) {
try {
return NumberFormat.getInstance().parse(txt.getText().toString()).floatValue();
} catch (ParseException e) {
return 0.0f;
}
}
Do NOT use Float.valueOf() if you want the code to work in countries that use decimal comma instead of decimal point.

String stext = editText.getText().toString();
float text = Float.parseFloat(stext);

Related

Invalid Double " " on String to Double to String conversion

I am converting a textView to Double then performing calculations then converting back to a string. I see that when my textview = "" it is throwing the error invalid Double "".
I added a check on the length of the text view prior to the calculation but it still is throwing the error. Any help is appreciated.
public void afterTextChanged(Editable s) {
if (textView.toString().length() > 0) {
Double ini = Double.parseDouble(textView.getText().toString());
Double calc = ini * 3.2808;
//passwordEditText.setText(textView.getText());
passwordEditText.setText(Double.toString(calc));
} else {
passwordEditText.setText("");
}
}
Use the getText method to get the text from a TextView. The toString method returns something else - a textual representation of the view itself. You can also trim it, in case there is extra whitespace.
String text = textView.getText().toString().trim();
if (text.length() > 0) {
Double ini = Double.parseDouble(text);
May be you are getting an empty string as a value, try changing if condition to the following:
if (textView.toString().trim().length() > 0) {
//logic
}
String text = textView.getText().trim();
if (!text.isEmpty()) {
try {
double ini = Double.parseDouble(text);
double calc = ini * 3.2808;
} catch (NumberFormatException e) {
---
double being the primitive type, Double an object wrapper, a bit more circumstantial converting ("unboxing") to double.
However parseDouble uses the computer language format: with a decimal point and no thousands separators. For another locale like most European countries the decimal separator is a comma. For portability:
NumberFormat nf = NumberFormat.getInstance(); // Default
NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH); // Or fixed
try {
Number n = nf.parse(text);
double ini = n.doubleValue();
...
} catch (ParseException e) {
...
Even if parseDouble would suffice in your case, now thousand separators are possible. And for displaying numbers, a NumberFormat is even more useful.

Android NumberFormatException when parsing EditText

I'm writing an app that takes in an input from the AddBook class, allows it to be displayed in a List, and then allows the user to Search for their book. To this end, I'm creating a temporary EditText, binding it to the box where the user actually enters their search value, then (after ensuring that it is not empty) I compare what they've entered for the ISBN number with the ISBN numbers of each entry in the arrayList of <Book> custom objects, the list being named books.
Problem is, when I try to parse the EditText into an Int, it doesn't seem to work. I first tried using toString() on the EditText, then using Integer.parseInt() on the result of that method, but it hasn't worked out, as the conversion is seemingly unsuccessful;
All of the resources are in place and the code compiles properly, so those aren't the problems here.
EditText myEdTx = (EditText) findViewById(R.id.bookName);
if(myEdTx.getText().equals("")){Toast toast = Toast.makeText(this, "Please enter something for us to work with!", Toast.LENGTH_SHORT);
toast.show();}
else{
//resume here
for(int i=0; i<books.size(); i++)
{
Book tBook = new Book(i, null, null); tBook = books.get(i); String s=myEdTx.toString();
int tInt = Integer.parseInt(s);`
To get the string representation of an EditText's content, use:
String s = myEdTx.getText().toString();
Using toString() directly on the EditText gives you something like:
android.widget.EditText{40d31450 VFED..CL ......I. 0,0-0,0}
...which is clearly not what you want here.
You assume the user inputs a number into the text field, but that is unsafe, as you only get a string text (which theoretically can contain non-numbers as well). When I remember correctly, you can adjust a text field in android where a user only can input numbers, which should suit you more.
NumberFormatException occurs when Integer.parse() is unable to parse a String as integer, so, its better to Handle this exception.
String s = myEdTx.getText().toString();
try {
int tInt = Integer.parseInt(s);
} catch( NumberFormatException ex ) {
//do something if s is not a number, maybe defining a default value.
int tInt = 0;
}
So the current String here you are trying to parse is with white space in the line
and integer class unable to parse that white space. So use following code.
String s=myEdTx.getText().toString();
int tInt = Integer.parseInt(s.trim());
String s = myEdtx.getText().toString().trim();
int iInt = Integer.parseInt(s);

Java have a int value using setText

I'm trying to set an int value using jTextField and the setText method. But of course setText wants a String. How do I get round this? I'll give you a snippet of the code:
private void setAllTextFields(FilmSystem e){
getFilmNameTF().setText(e.getFilmName());
lectureTF.setText(e.getLecture());
ageTF.setText(e.getAge());
priceTF.setText(e.getTicketCost());
seatsTF.setText(e.getNoOfSeats());
seatsTF is a jTextField and getNoOfSeats is a method in another class that returns a int value.
Thanks again for answering this question. Now how would I go about getting the value of the int to do something to do?
public void buyTicket() {
String newFilmName = filmNameTF.getText();
String newLecture = lectureTF.getText();
String newAge = ageTF.getText();
String newPrice = priceTF.getText();
int newSeats = seatsTF.
As you can see the code, the String values I can get easy with getText. I can then print them out or whatever with them. How can I do this with the seats int? Thanks again.
String#valueOf convert your int to String.
String.valueOf(e.getAge()); will return the string representation of the int argument.
seatsTF.setText(String.valueOf(e.Age()));
...
USe
seatsTF.setText(""+e.getNoOfSeats());
OR
seatsTF.setText(String.valueOf(e.getNoOfSeats()));
Normal ways would be
seatsTF.setText(Integer.toString(e.getNoOfSeats()));
or
seatsTF.setText(String.valueOf(e.getNoOfSeats()));
but, this can be achieved with a concatenation like this:
seatsTF.setText("" + e.getNoOfSeats());
Assuming age field is of type int, you could try something like:
ageTF.setText( Integer.toString(e.getAge()) );
Setting an int converting it to a String not a big deal. Displaying a value is a problem. To take care of how the value is displayed properly in the textfield you may use a DecimalFormat to format the numeric value. But may be the number is locale specific then you need NumberFormat instance
NumberFormat nf = NumberFormat.getInstance(locale);
nf.setMaximumIntegerDigits(12);
nf.setMaximumFractionDigits(0);
nf.setMinimumFractionDigits(0);
String s = nf.format(e.getNoOfSeats());
seatsTF.setText(s);
You may also need to read the tutorial on how to use the DecimalFormat.
To convert Integer Value to String you should
MedicineTM medicine=tblmedicine.getSelectionModel().getSelectedItem();
txtmedicine.setText(medicine.getMID());
txtDescription.setText(medicine.getDescription());
txtQty.setText(String.valueOf(medicine.getQty())); // this is what i did
cmbApproval.setValue(medicine.getApproval());
I think you should write the code as
seatsTF.setText(e.getNoOfSeats().toString());

Android Println() to a TextView

I would like to take some variables, listed here;
double dBench = (((Math.floor((dWeight*.664)/10))*10)-10)+dPush;
double dFlies = (dBench)*.6;
double dCurls = (dWeight*dPull)*.25;
double dLats = ((Math.floor((dWeight*.5)/10))*10);
System.out.println(dBench);
System.out.println(dFlies);
System.out.println(dCurls);
System.out.println(dLats);
But how do I get the println()'s to print to a textview or something? Thanks.
You do not have to do println to textview. TextView has method called setText and getText. setText can set text to TextView and getText can get text from textview. Look here for more info.
Android Tutorial for TextView
For double,
textView = (TextView)findViewById(R.id.myTextView);
textView.setText(String.valueOf(Your double value));
Use the textview's set text method
textView = (TextView)findViewById(R.id.myTextView);
textView.setText("This text will be placed in the textView");
For a double value it will look like this
textView = (TextView)findViewById(R.id.myTextView);
textView.setText(String.valueOf(double_variable);
In case you want to print a value in textView:
TextiView textView = (TextView) findViewById(R.id.textViewId);
textView.setText(...see below...);
Integer: Integer.valueOf(integerVariable).toString()
the same can be done with Long, Double etc. Here is analogic example for Double:
double a = some value;
String toShow = Double.valueOf(a).toString();
textView.setText(toShow);
If you want to check those values (debug) you can use Log class.
Log.d("VALUE", Integer.valueOf(integerVariable).toString());
In this case the value will be shown in LogCat (tag VALUE). You can filter messages typing tag:VALUE
Integer, Long, Double are wrapper classes for primitives and those classes have toString() method which you can use to pass String into the TextView.
If you want to see the value which is stored into variables you can use log cat commands to print them into console as follows:
Log.v("Title" , variable_name);
or for numeric value you can use
textView = (TextView)findViewById(R.id.myTextView);
textView.setText(""+Your double value);

Getting the a text from EditText (but a Number)

I know that you can get a normal text like this:
EditText input = (EditText) findViewById(R.id.input);
String value = input.getText().toString();
but now I need a to an input like this: 0xFFFFFF (a Hex-Color), an Integer... But value is only a String and I don't know how to convert it... I'm using view.setBackgroundColor(color);
Thanks a lot!
you can use the Color.parseColor(colorString); function to convert your string to a color int

Categories

Resources