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