I'm using a TextWatcher for editing values while entering in EditText
here is my TextWatcher
public class NumberTextWatcher implements TextWatcher {
private DecimalFormat df;
private DecimalFormat dfnd;
private boolean hasFractionalPart;
private EditText et;
public NumberTextWatcher(EditText et)
{
df = new DecimalFormat("#,###");
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###");
this.et = et;
hasFractionalPart = false;
}
#SuppressWarnings("unused")
private static final String TAG = "NumberTextWatcher";
#Override
public void afterTextChanged(Editable s)
{
et.removeTextChangedListener(this);
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= et.getText().length()) {
et.setSelection(sel);
} else {
// place cursor at the end?
et.setSelection(et.getText().length() - 1);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}
et.addTextChangedListener(this);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator())))
{
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
after that, I try to Parse the values to doubles using this code :
String amount1 = amount.getText().toString().replaceAll("[^\\d]", "");
String duration1 = duration.getText().toString().replaceAll("[^\\d]", "");
String interest1 = interest.getText().toString().replaceAll("[^\\d]", "");
But the problem i have is that when Device Default language is not English, it can parse the string to Doubles, so i think i set US Locale for editTexts! is this possible? if not, what should i do in order to be able to parse values to doubles?
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US);
When you have control over the back-end I find it easiest to deal with what language you are expecting and have done extensive tests on. Therefore, when handling file IO on files that I have internally, I always call the call that you have at the end of your comment there before any file creation code is performed. In my case it would be
final DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH); //Format our data to two decimal places for brightness change.
String stringFormat = "#0.00";
decimalFormat.applyPattern(stringFormat);
decimalFormat.format(dataString);
Then, no matter what language the device is actually set to, you are always dealing with the locale that you are accustomed to. And this will aide in handling other languages that might use different number formats for instance in this case since I was handling numerics. Since you are dealing with doubles you might be approaching this numeric translation issue. But if you are dealing with inputs from an EditText, this particular approach that was only on my back-end might not be applicable. But I thought communicating my approach might still be somewhat helpful; hopefully anyways. Doesn't hurt to share.
Related
This question already has answers here:
Is there a way to define a min and max value for EditText in Android?
(29 answers)
Closed 11 months ago.
I am creating an app that calculates the the users marks. How do I go forward, I'm trying to limit the user's input value to between min=0 and max=100?
I've got 3 inputs that I want to limit.
EditText a = (EditText) findViewById(R.id.Assignment1);
EditText b = (EditText) findViewById(R.id.Assignment2);
EditText c = (EditText) findViewById(R.id.Assignment3);
Tried using the following but only works when I execute my function.
public void YearMark(View v)
{
EditText a = (EditText) findViewById(R.id.Assignment1);
a.setFilters(new InputFilter[]{ new InputFilterMinMax("0", "100")});
As #JAY_Panchal mentioned, you can use an InputFilter:
public class RangeInputFilter implements InputFilter {
private final int min, max;
public RangeInputFilter(int min, int max) {
boolean rightOrder = min <= max;
this.min = rightOrder ? min : max;
this.max = rightOrder ? max : min;
}
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dStart, int dEnd) {
try {
String sourceStr = source.toString();
String destStr = dest.toString();
String result = destStr.substring(0, dStart) + sourceStr.substring(start, end) + destStr.substring(dEnd);
int input = Integer.parseInt(result);
if (min <= input && input <= max) return null;
} catch (NumberFormatException ignored) { }
return "";
}
}
When a user changes the content of an EditText, you can use an InputFilter to decide what actually changes in the EditText.
Returning null means that the input is accepted.
Returning something else (in this case "") means that source should be replaced with that (in this case, we want dest to stay as it is and thus have an empty source).
To assign your filter:
RangeInputFilter filter = new RangeInputFilter(0, 100);
InputFilter[] filters = new InputFilter[] {filter};
editText1.setFilters(filters);
editText2.setFilters(filters);
editText3.setFilters(filters);
Add this textwatcher for all three edittext a,b and c:
a.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
String strTest = editText1235.getText().toString().trim();
if (!strTest.equals("")) {
float no = Float.parseFloat(strTest);
if (no > 100) {
a.setText(null);
Toast.makeText(this, "enter a value less than 100", Toast.LENGTH_SHORT).show();
}
}
}
});
Also set input type of these text fields as number so that user cannot enter a negative sign,ie, any value less than 0.
android:inputType="number"
While submitting the details also check if the field is not empty like below:
if (a.getText().toString().trim().length() <=0 ||b.getText().toString().trim().length() <=0 ||c.getText().toString().trim().length() <= 0){
Toast.makeText(this, "Value cannot be empty", Toast.LENGTH_SHORT).show();
}
I don't know your usecase, but you might also want to use a SeekBar.
A SeekBar is a slider - you can select a number by sliding. It is also very customizable.
The main advantage is that the user does not need to open the keyboard.
I am a complete noob to java programming and have thrown myself in at the deep end, as per usual (I seem to get better results that way).
I am creating an Android app with Android Studio and have come across an error in my Java code.
I have searched for an answer but the answers are all very specific to the actual code so cannot find any answers on my own.
My problem arises in my MainActivity.java where i am using TextWatcher as a NumberTextWatcher that will convert and set any input to decimal currency (as the user will be inputting a price) from this answer on Stack Overflow.
The problem is that I am getting an error:
Cannot resolve method setText()
Here is the code where the error is (I have marked the errors with //<- Here it throws an error.):
public class NumberTextWatcher implements TextWatcher {
private final DecimalFormat df;
private final DecimalFormat dfnd;
private final EditText et;
private boolean hasFractionalPart;
private int trailingZeroCount;
NumberTextWatcher(EditText inputPricePerOz, String pattern) {
df = new DecimalFormat(pattern);
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###.00");
this.et = inputPricePerOz;
hasFractionalPart = false;
}
#Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener();
if (s != null && !s.toString().isEmpty()) {
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "").replace("$","");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
StringBuilder trailingZeros = new StringBuilder();
while (trailingZeroCount-- > 0)
trailingZeros.append('0');
et.setText(); //<- Here it throws an error.
} else {
et.setText(); //<- Here it throws an error.
}
et.setText(); //<- Here it throws an error.
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel < et.getText().length()) {
et.setSelection(sel);
} else if (trailingZeroCount > -1) {
et.setSelection(et.getText().length() - 3);
} else {
et.setSelection(et.getText().length());
}
} catch (NumberFormatException | ParseException e) {
e.printStackTrace();
}
}
et.addTextChangedListener(this);
}
As I know very little about Java I do not know why this error is occurring, although I would think that setting text with the setText() method would be simple enough.
Any help would be very much appreciated
Wrong syntax: It should be like below any one
et.setText("Text to set in editext");
OR
et.setText(R.string.app_name);
OR
et.setText("Text to set in editext", BufferType.EDITABLE);
Refer the API Doc :
https://developer.android.com/reference/android/widget/EditText.html#setText(java.lang.CharSequence, android.widget.TextView.BufferType)
&
https://developer.android.com/reference/android/widget/TextView.html#setText(java.lang.CharSequence)
If you check the documentation for EditText you will see that the method takes a string and a buffer type. So you need to add the text you wish to change to and the buffertype. You probably want TextView.BufferType.EDITABLE.
e.g.
et.setText("Example text", TextView.BufferType.EDITABLE);
see more here https://developer.android.com/reference/android/widget/EditText.html
So I figured out why the error is being thrown out, its a simple mistake that I cannot explain but when I copied and pasted the code it somehow missed out copying certain parts, or failing that android studio/gradle changed my code, here is the fixed code:
#Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this); //<- also fixed error an error here
if (s != null && !s.toString().isEmpty()) {
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "").replace("$","");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
StringBuilder trailingZeros = new StringBuilder();
while (trailingZeroCount-- > 0)
trailingZeros.append('0');
et.setText(df.format(n) + trailingZeros.toString()); //<- Fixed error
} else {
et.setText(dfnd.format(n)); //<- Fixed error
}
et.setText("$".concat(et.getText().toString())); //<- Fixed error
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel < et.getText().length()) {
et.setSelection(sel);
} else if (trailingZeroCount > -1) {
et.setSelection(et.getText().length() - 3);
} else {
et.setSelection(et.getText().length());
}
} catch (NumberFormatException | ParseException e) {
e.printStackTrace();
}
}
et.addTextChangedListener(this);
}
I'm working in an Android application and i want to create a decimal mask for editText in android. I want a mask like a maskMoney jQuery plugin. But in some cases my number will have 2 decimal places, 3 decimal places or will be a integer. I want do something like this:
When the EditText is created, come with a default value: 00.01
If user press the number 2, the result should be: 00.12
If user press the number 3, the result should be: 01.23
If user press the number 4, the result should be: 12.34
If user press the number 5, the result should be: 123.45
If user press the number 6, the result should be: 1,234.56
What's the best way to do that?
I resolved with this:
public static TextWatcher amount(final EditText editText, final String metric) {
return new TextWatcher() {
String current = "";
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().equals(current)) {
editText.removeTextChangedListener(this);
String cleanString = s.toString();
if (count != 0) {
String substr = cleanString.substring(cleanString.length() - 2);
if (substr.contains(".") || substr.contains(",")) {
cleanString += "0";
}
}
cleanString = cleanString.replaceAll("[,.]", "");
double parsed = Double.parseDouble(cleanString);
DecimalFormat df = new DecimalFormat("0.00");
String formatted = df.format((parsed / 100));
current = formatted;
editText.setText(formatted);
editText.setSelection(formatted.length());
editText.addTextChangedListener(this);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void afterTextChanged(Editable s) {}
};
}
Do you know of any method to make sure users can only enter figures with a maximum number of decimals.
I'm not sure how to address this problem. In the MS SQL database I'm going to send data from my app I've got columns with this type decimal(8,3)
Now considering the data type of the column that's finally going to store the value I want to validate in Android, I've considered these two cases:
If the user enters a number with no decimals, the maximum number of digits must be 8
If the user enters a number with decimals, the maximum number of digits must be 8 (including the digits to the right of the decimal point)
Now I'm sure about the first case, but not so much about the second. Is it right to keep the number of maximum digits fixed(for example, always 8)? Or should I consider allowing a maximum of 8 digits to the left and 3 to the right of the decimal point?
Either way this is what I've been trying in Android:
mQuantityEditText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
String str = mQuantityEditText.getText().toString();
DecimalFormat format = (DecimalFormat) DecimalFormat
.getInstance();
DecimalFormatSymbols symbols = format.getDecimalFormatSymbols();
char sep = symbols.getDecimalSeparator();
int indexOFdec = str.indexOf(sep);
if (indexOFdec >= 0) {
if (str.substring(indexOFdec, str.length() - 1).length() > 3) {
s.replace(0, s.length(),
str.substring(0, str.length() - 1));
}
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
Even though, the above code handles the maximum number of decimal places. It does not limit the total number of digits allowed in the EditText.
Do you think you could help me improve my code so that it handles both the maximum number of decimal places and the total number of digits allowed in a EditText (considering both numbers to the left and to the right of the decimal point)
EDIT
Well, now I'm trying what João Sousa suggested and here's what I've tried:
1) I defined a class that implements InputFilter
public class NumberInputFilter implements InputFilter {
private Pattern mPattern;
public NumberInputFilter(int precision, int scale) {
String pattern="^\\-?(\\d{0," + (precision-scale) + "}|\\d{0," + (precision-scale) + "}\\.\\d{0," + scale + "})$";
this.mPattern=Pattern.compile(pattern);
}
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned destination, int destinationStart, int destinationEnd) {
if (end > start) {
// adding: filter
// build the resulting text
String destinationString = destination.toString();
String resultingTxt = destinationString.substring(0, destinationStart) + source.subSequence(start, end) + destinationString.substring(destinationEnd);
// return null to accept the input or empty to reject it
return resultingTxt.matches(this.mPattern.toString()) ? null : "";
}
// removing: always accept
return null;
}
}
2) Tried to use the class like this :
mQuantityEditText.setFilters(new InputFilter[] { new NumberInputFilter(8,3)} );
I would go for a filter in the edit text itself with the power of regex. First the regex expression:
^\-?(\d{0,5}|\d{0,5}\.\d{0,3})$
Maybe there are multiple ways to improve this expression, but this does trick.
And now just set an input filter in the edittext, like this:
final String regex = "^\-?(\d{0,5}|\d{0,5}\.\d{0,3})$";
((EditText)rootView.findViewById(R.id.editText1)).setFilters(new InputFilter[] {
new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned destination, int destinationStart, int destinationEnd) {
if (end > start) {
// adding: filter
// build the resulting text
String destinationString = destination.toString();
String resultingTxt = destinationString.substring(0, destinationStart) + source.subSequence(start, end) + destinationString.substring(destinationEnd);
// return null to accept the input or empty to reject it
return resultingTxt.matches(regex) ? null : "";
}
// removing: always accept
return null;
}
}
});
Btw, I just tested this code and what it does is:
The user can enter a maximum of 8 digits;
As soon as the user enters a '.', the maximum decimal digits allowed are 8.
Did I correctly understand the problem you described?
-- EDIT
Ok, I was almost there. From what I understand, decimal(8,3) means at most 8 digits including digits to the left or right of the decimal point, ranging from -99999.999 to 99999.999.
At least that's what I understand from this sentence Standard SQL requires that DECIMAL(5,2) be able to store any value with five digits and two decimals, so values that can be stored in the salary column range from -999.99 to 999.99. Even though it's from the MySQL documentation the MSSQL docs seem to do the same.
I have answser for you, me also suffered lot in this kind of situation.:D :P
I have implemented this for maximum of 4 digits to the left and 2 to the right of the decimal point ex: 4444.99
so small changes need to implement what i did:
Need to do following changes
1) copy CustomTextWatcher.java to track input of editText.
import java.text.NumberFormat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
public class CustomTextWatcher implements TextWatcher {
private NumberFormat nf = NumberFormat.getNumberInstance();
private EditText et;
private String tmp = "";
private int moveCaretTo;
private static final int INTEGER_CONSTRAINT = 4;
private static final int FRACTION_CONSTRAINT = 2;
private static final int MAX_LENGTH = INTEGER_CONSTRAINT
+ FRACTION_CONSTRAINT + 1;
public CustomTextWatcher(EditText et) {
this.et = et;
nf.setMaximumIntegerDigits(INTEGER_CONSTRAINT);
nf.setMaximumFractionDigits(FRACTION_CONSTRAINT);
nf.setGroupingUsed(false);
}
public int countOccurrences(String str, char c) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count++;
}
}
return count;
}
#Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this); // remove to prevent stackoverflow
String ss = s.toString();
int len = ss.length();
int dots = countOccurrences(ss, '.');
boolean shouldParse = dots <= 1
&& (dots == 0 ? len != (INTEGER_CONSTRAINT + 1)
: len < (MAX_LENGTH + 1));
if (shouldParse) {
if (len > 1 && ss.lastIndexOf(".") != len - 1) {
try {
if (ss.contains(".")) {
String[] integerFractionStrings = ss.split("\\.");
Log.v("Check SS ", ss);
Log.v("second string", "Found"
+ integerFractionStrings.length);
if (integerFractionStrings.length > 1) {
Log.v("integerFractionStrings",
integerFractionStrings[1]);
if (integerFractionStrings[1].length() == 1
&& integerFractionStrings[1].charAt(0) == '0') {
et.setText(ss);
Log.v("second string", "size 1");
} else {
Log.v("second string", "> 1");
Double d = Double.parseDouble(ss);
if (d != null) {
et.setText(nf.format(d));
}
}
}
} else {
Log.v("First string", "No dot");
Double d = Double.parseDouble(ss);
if (d != null) {
et.setText(nf.format(d));
}
}
} catch (NumberFormatException e) {
}
}
} else {
Log.v("second string", "size 1");
et.setText(tmp);
}
et.addTextChangedListener(this); // reset listener
// tried to fix caret positioning after key type:
if (et.getText().toString().length() > 0) {
if (dots == 0 && len >= INTEGER_CONSTRAINT
&& moveCaretTo > INTEGER_CONSTRAINT) {
moveCaretTo = INTEGER_CONSTRAINT;
} else if (dots > 0 && len >= (MAX_LENGTH)
&& moveCaretTo > (MAX_LENGTH)) {
moveCaretTo = MAX_LENGTH;
}
try {
et.setSelection(et.getText().toString().length());
// et.setSelection(moveCaretTo); <- almost had it :))
} catch (Exception e) {
}
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
moveCaretTo = et.getSelectionEnd();
tmp = s.toString();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int length = et.getText().toString().length();
if (length > 0) {
moveCaretTo = start + count - before;
}
}
}
2) set this class to check your editText by following.
EditText review_food_Price;
review_food_Price = (EditText) findViewById(R.id.food_Price);
review_food_Price.setRawInputType(InputType.TYPE_CLASS_NUMBER
| InputType.TYPE_NUMBER_FLAG_DECIMAL);
review_food_Price.addTextChangedListener(new CustomTextWatcher(
review_food_Price));
Hope you can convert my code according to your need.
The problem that you describe is precisely what a Masked EditText is meant to be used for. :)
i'm using a NumberTextWatcher for realtime-edit for an EditText and it's working fine for me,
but some users reporting that they got NumberException problem, i think this is because numbers changes in 123,456 in EditText and cant parse to doubles, so i did some change and use Replace("," , "") code but this is not working for some too!
what should i do so this code works for all of my users?
Thanks and Sorry for my Poor English :D
NumberTextWatcher:
public NumberTextWatcher(EditText et)
{
df = new DecimalFormat("#,###");
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###");
this.et = et;
hasFractionalPart = false;
}
#SuppressWarnings("unused")
private static final String TAG = "NumberTextWatcher";
#Override
public void afterTextChanged(Editable s)
{
et.removeTextChangedListener(this);
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= et.getText().length()) {
et.setSelection(sel);
} else {
// place cursor at the end?
et.setSelection(et.getText().length() - 1);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}
et.addTextChangedListener(this);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator())))
{
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
And Here is MainActivity:
final EditText amount = (EditText) findViewById(R.id.editText1);
final EditText duration = (EditText) findViewById(R.id.editText2);
final EditText interest = (EditText) findViewById(R.id.editText3);
amount.addTextChangedListener(new NumberTextWatcher(amount));
duration.addTextChangedListener(new NumberTextWatcher(duration));
interest.addTextChangedListener(new NumberTextWatcher(interest));
String amount1 = amount.getText().toString().replaceAll(",", "");
String duration1 = duration.getText().toString().replaceAll(",", "");
String interest1 = interest.getText().toString().replaceAll(",", "");
try{
double i = Double.parseDouble(amount1);
double j = Double.parseDouble(duration1);
double z = Double.parseDouble(interest1);
}
catch(NumberFormatException e){
}
Programs store and operate on numbers in a locale-independent way. Before displaying or printing a number, a program must convert it to a String that is in a locale-sensitive format. For example, in France the number 123456.78 should be formatted as 123 456,78, and in Germany it should appear as 123.456,78. So you can't just replace "," and ".".
The following code is an example on how to convert from double and back using the current currency of a user in the United States.
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Currency;
import java.util.Locale;
public class Test
{
public static void main(String[] args)
{
Locale currentLocale = Locale.getDefault();
Currency currentCurrency = Currency.getInstance(currentLocale);
Double currencyAmount = new Double(9876543.21);
NumberFormat currencyFormatter =
NumberFormat.getCurrencyInstance(currentLocale);
System.out.println(NumberFormat.getNumberInstance(currentLocale));
System.out.println(
currentLocale.getDisplayName() + ", " +
currentCurrency.getDisplayName() + ": " +
currencyFormatter.format(currencyAmount));
try
{
System.out.println(currencyFormatter.parseObject("$9,876,543.21"));
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
What else could you do:
* make sure users are entering properly formatted numbers. For example, you should not see any other chars except numbers , . + - $, etc.
* IF you know the user will ALWAYS enter two decimal digits, for example, 10 dollars would be expressed as 10.00 (or 10,00), then you can safely remove all "," and "." and get the original number by dividing it by 100, but remember to also remove spaces (remember France :) )
Also, check the documentation: http://docs.oracle.com/javase/tutorial/i18n/format/numberFormat.html
The problem is probably that other users might be inputting ill-formatted numbers. So you are just replacing the commas with white spaces. Maybe you should replace all non-digit characters?
amount1 = amount.getText().toString().replaceAll("[^\\d]", "");
Or if you want them to leave the decimal points then use the following:
amount1 = amount.getText().toString().replaceAll("[^\\d.]", "");