I am trying to read in multiple variables (int, double, String) from one input. However, the input has to be a specific way, i.e. the user should enter either distance in miles by entering “X miles” (either in decimals or as an integer) or time by entering “Y mins” (only as an integer). Here is an example of what I coded. However, enter a double does not work. I also need to use these values in other methods.
public boolean hintWalkTracker() {
// tracks whether the input for walking/running activity is correct
String text = String.valueOf(hintEditText.getText());
String s = text.replaceAll("\\d","");
int i = Integer.parseInt(text.replaceAll("[\\D]", ""));
double d = Double.parseDouble(text.replaceAll("[\\D]", ""));
if ((activityDropDown.getSelectedItem().equals("Walking") || activityDropDown.getSelectedItem().equals("Running")) && s.equals(" miles")) {
d = d * 88.9;
return true;
} else if ((activityDropDown.getSelectedItem().equals("Walking") || activityDropDown.getSelectedItem().equals("Running")) && s.equals(" mins")) {
d = i * 4.78;
return true;
} else if ((activityDropDown.getSelectedItem().equals("Walking") || activityDropDown.getSelectedItem().equals("Running")) && ((!s.equals(" mins")) || !s.equals(" miles"))) {
// create a new AlertDialog Builder
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
// set dialog's message to display
builder.setMessage(R.string.walk_missing_message);
// provide an OK button that simply dismisses the dialog
builder.setPositiveButton(R.string.OK, null);
// create AlertDialog from the AlertDialog.Builder
AlertDialog errorDialog = builder.create();
errorDialog.show(); // display the modal dialog
return false;
}
return false;
}
You just need to use a TextWatcher on your EditText in order to check what the user is writing and to react as you want when he write what you need.
Code sample :
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
hintWalkTracker();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Related
I'm using editText in recyclerView, I want to display or edit the 2nd one only if the 1st is filled android java.
This is a quick solution of mine:
In your adapter, create a flag int currentFilled = -1;
and update this flag whenever your editText is filled
Like this:
EditText edt1 = new EditText(this);
edt1.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void afterTextChanged(Editable s) { }
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() >0){
// this is when your edt1 is filled
// edt2.setEnabled(true); // You can enable your edt2 or whatever here
// edt2.setVisibility(View.VISIBLE);
currentFilled = itemPosition;
notifyItemChanged(itemPosition+1) // position you wan to display or edit the edt
} else {
// when edt1 is not filled
/// TODO do what ever you want
}
}
});
Then in your ViewHolder check if currentFilled == itemPosition-1
==>>
edt.setEnabled(true); // You can enable your edt2 or whatever here
// or
edt.setVisibility(View.VISIBLE)
it's may get some issues or not depending on your requirements.
Happy coding :))
I need help on my code.
I have an editText where the user enters the opening and closing time of the store and there is a checkbox with "Close".
The user enters the opening time 09:00 and then with the Text Watcher I add a space and a dash and the user enters the closing time 19:00, so that at the end the time is 09:00 - 19:00.
For example, if the store is closed on Saturday, the user must click on the checkbox and when the checkbox is clicked, the editText has the text set and it says "Closed".
The problem is that when I use the Text Watcher, if the length is equal to 6, it adds the hyphen and then when the user clicks on the checkbox instead of writing "Closed" it says "Closed-".
How can I remove that dash?
There is a condition where the Text Watcher turns off when there are only letters in the editText.
Does anyone have a solution to my problem, do you have any advice for me?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert__orari);
lunedi_inizio_uno = (EditText)findViewById(R.id.editText_uno_lunedi_inizio);
lunediUno = (CheckBox)findViewById(R.id.checkBox_uno_lunedi);
lunedi_inizio_uno.addTextChangedListener(new TextWatcher() {
int keyDell;
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
lunedi_inizio_uno.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL)
keyDell = 1;
int prevL = 0;
return false;
}
});
if (keyDell == 0) {
int len = lunedi_inizio_uno.getText().length();
if(len == 5) {
lunedi_inizio_uno.setText(lunedi_inizio_uno.getText() + " ");
lunedi_inizio_uno.setSelection(lunedi_inizio_uno.getText().length());
}if(len == 6) {
lunedi_inizio_uno.setText(lunedi_inizio_uno.getText() + "-");
lunedi_inizio_uno.setSelection(lunedi_inizio_uno.getText().length());
}if(len == 7) {
lunedi_inizio_uno.setText(lunedi_inizio_uno.getText() + " ");
lunedi_inizio_uno.setSelection(lunedi_inizio_uno.getText().length());
}
} else {
keyDell = 0;
}
}
#Override
public void afterTextChanged(Editable arg0) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
});
lunediUno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
lunedi_inizio_uno.setText("Chiuso");
}
}
});
}
I solved the problem, it was enough to add "-" in the length equal to 5 and eliminate the conditions of length equal to 6 and 7.
The code below produce an stackoverflow error. The idea is to format the amount when or after user type an amount.
500 -> 500.00
1000 -> 1 000.00
29999.55-> 29 999.55
..
..
..
edit_amount.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
if (edit_amount.getText().toString().length()>0){
edit_amount.setText(
currencyFormat(edit_amount.getText().toString()));
}else {}
}
});
public String currencyFormat(String number){
String credits="";
try {
//en, us
if (TextUtils.isEmpty(MyApplication.pref.GetPreferences("AppCurrency"))){
credits = NumberFormat.getCurrencyInstance(new Locale("fr", "FR")).format(Double.valueOf(number));
}else {
if (MyApplication.pref.GetPreferences("AppCurrency").equals("Euro")) {
credits = NumberFormat.getCurrencyInstance(new Locale("fr", "FR")).format(Double.valueOf(number));
} else {
credits = NumberFormat.getCurrencyInstance(new Locale("en", "US")).format(Double.valueOf(number));
}
}
}catch(Exception ex){
credits = "mCredits";
}
return credits;
}
Your code doesn't work because when you call edit_amount.setText(...) then the afterTextChanged(Editable s) is triggered and then edit_amount.setText(...) is triggered and so on. You need to change your logic to do what you want and avoid stack overflow.
For example you could unregister TextWatcher, setText and then register it again.
Alternatively, you can set a flag so that your TextWatcher knows when you change the text yourself and then instruct TextWatcher to ignore it.
To avoid recursive invocation of afterTextChanged callback you can set up additional chek. Smth like this
#Override
public void afterTextChanged(Editable s) {
if (et.getText().toString().length() > 0) {
String src = et.getText().toString();
String origin = currencyFormat(src);
if(!src.equals(origin)) {
et.setText(currencyFormat(et.getText().toString()));
}
}
}
Try below code :
private String current = "";
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(!s.toString().equals(current)){
[your_edittext].removeTextChangedListener(this);
String cleanString = s.toString().replaceAll("[$,.]", "");
double parsed = Double.parseDouble(cleanString);
String formatted = NumberFormat.getCurrencyInstance().format((parsed/100));
current = formatted;
[your_edittext].setText(formatted);
[your_edittext].setSelection(formatted.length());
[your_edittext].addTextChangedListener(this);
}
}
This question already has answers here:
How to Automatically add thousand separators as number is input in EditText
(16 answers)
Closed 6 years ago.
I want to add commas between each 1,000 in EditText, so the user wont have to "guess" if it is 10,000 or 100,000. In EditText when you input a number it is displayed like 10000 but I want to display it like 10,000. How can that be done?
You have to add TextChangedListner to your edittext .i.e
et.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
try {
String givenstring = s.toString();
Long longval;
if (givenstring.contains(",")) {
givenstring = givenstring.replaceAll(",", "");
}
longval = Long.parseLong(givenstring);
DecimalFormat formatter = new DecimalFormat("#,###,###");
String formattedString = formatter.format(longval);
et.setText(formattedString);
et.setSelection(et.getText().length());
// to place the cursor at the end of text
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
et.addTextChangedListener(this);
}
});
Note : Make sure that your edittext inputtype is number. i.e android:inputType="number"
Attach a TextChangedListener to EditText using :
editText.addTextChangedListener();
Refer the below javadoc of TextWatcher :
http://developer.android.com/reference/android/text/TextWatcher.html
New SO user here and fairly new to Java. Upon running this, it crashes with a java.lang.stackoverflow error. I'm fairly certain it is recursive but I can't figure out why. I've tried stepping through debugging but I get an error that it can't find the class file. Here is the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newPrice.addTextChangedListener(tradeWatch);
tradeIn.addTextChangedListener(tradeWatch);
acc.addTextChangedListener(tradeWatch);
tradeDif.addTextChangedListener(tradeWatch);
}
TextWatcher tradeWatch = new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
calcTrade();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
private void calcTrade() {
Editable eValue1 = newPrice.getText(), eValue2 = tradeIn.getText(), eValue3 = acc.getText();
Double value1 = 0.0, value2 = 0.0, value3 = 0.0, result = 0.0;
if (eValue1 != null)
value1 = toDouble(eValue1);
if (eValue2 != null)
value2 = toDouble(eValue2);
if (eValue3 != null)
value3 = toDouble(eValue3);
if (value1 != null && value2 != null && value3 != null)
result = value1 - (value2 + value3);
tradeDif.setText(result.toString());
}
private double toDouble(final Editable editable) {
final String content = editable.toString();
if (content.isEmpty()) {
return 0;
}
return Double.parseDouble(content);
}
public void nextPage(View v) {
Intent i=new Intent(this, Activity2.class);
startActivity(i);
}
}
Problem is line:
tradeDif.setText(result.toString());
You change text and it causes to call
afterTextChanged(Editable s)
again and again.
Simple solution
Remove listener
Change value
Add listener
The problem is that your tradeDif is using your tradeWatch TextWatcher. In that TextWatcher's afterTextChanged(), you call calcTrade(), which calls tradeDif.setText(result.toString());.
After Android finishes setting the text on tradeDif, it will again call afterTextChanged() on your TextWatcher, and it will continue doing so until you stop setting tradeDif's text.