Reputation: 103
I have two TextView
's that display averages from couple of EditText boxes and display them as "My Avg: 245" and the other Textview
has "My Avg: 145". I'm calculating the avg in these two TextView
's on a button click and setting the text of the button to the answer. How do I get only the number from both the text view? Because when call Double.parseDouble()
on the TextView, I'm getting an error. Any help would be appreciated, thanks.
Upvotes: 0
Views: 1791
Reputation: 4112
Get String from all EditText and extract number from string using Regex. Check below example:
String str = "My Avg: 145";
Pattern pattern = Pattern.compile("(\\d+)");
Matcher m = pattern.matcher( str );
if( m.find() ){
String i=m.group();
System.out.println( "-->>" + i);
}
Here
\d means one digit
\d+ means one or more digits
() means capture that group
This regrx will give you first group of digits in your string. You can parse i
using double.parse();
Upvotes: 3
Reputation: 838
What do you mean by calculating the average in the textview? wherever you do that calculation you should be able to access the values, trying to parse the value from the textview is not a very good practice.
Share your code and the error you are getting, i'm guessing that you are trying to parse the value with the complete string of the textview and, as you can imagine, is not possible to get the Double value from a String.
If the String My avg:
never changes, then you split this string from the ":" symbol and trim the value.
String text = "My avg: 245";
String numberString = text.split(":")[1];
Double number = Double.parseDouble(numberString);
System.out.println(number);
the output is:
245.0
I insist that you should not this approach, if the text changes by any reason, your app will break.
Upvotes: 2
Reputation: 2208
You can get number from text view like following :
String textView = tv.getText().toString();
if (!textView.equals("") && !textView.equals(......)) {
int num = Integer.parseInt(textView);//extract number from text view
}
Upvotes: 2
Reputation: 3346
You can not directly call Double#parseDouble
on a String
as it might throw NumberFormatException
if its not a number.
So, you will have to get the number out of it first. You can do it by using String#split
.
Get the String using the TextView#getText()
The split the text using,
String[] val = textViewText.split(":");
This will return an array, you can then call Double.parseDouble
,
double num = Double.parseDouble(val[1].trim());
Upvotes: 1