See my comment above to understand your issue. You might use this to verify the user input with your textwatcher:
SimpleDateFormat formatter =
new SimpleDateFormat("MM/yy", Locale.GERMANY);
Calendar expiryDateDate = Calendar.getInstance();
try {
expiryDateDate.setTime(formatter.parse(mExpiryDate.getText().toString()));
} catch (ParseException e) {
//not valid
}
// expiryDateDate has a valid date from the user
So in complete it would be:
String lastInput ="";
@Override
public void afterTextChanged(Editable s) {
String input = s.toString();
SimpleDateFormat formatter = new SimpleDateFormat("MM/yy", Locale.GERMANY);
Calendar expiryDateDate = Calendar.getInstance();
try {
expiryDateDate.setTime(formatter.parse(input));
} catch (ParseException e) {
if (s.length() == 2 && !lastInput.endsWith("/")) {
int month = Integer.parseInt(input);
if (month <= 12) {
mExpiryDate.setText(mExpiryDate.getText().toString() + "/");
}
}else if (s.length() == 2 && lastInput.endsWith("/")) {
int month = Integer.parseInt(input);
if (month <= 12) {
mExpiryDate.setText(mExpiryDate.getText().toString().subStr(0,1);
}
}
lastInput = mExpiryDate.getText().toString();
//because not valid so code exits here
return;
}
// expiryDateDate has a valid date from the user
// Do something with expiryDateDate here
}
Finally the complete solution:
String input = s.toString();
SimpleDateFormat formatter = new SimpleDateFormat("MM/yy", Locale.GERMANY);
Calendar expiryDateDate = Calendar.getInstance();
try {
expiryDateDate.setTime(formatter.parse(input));
} catch (ParseException e) {
} catch (java.text.ParseException e) {
if (s.length() == 2 && !mLastInput.endsWith("/")) {
int month = Integer.parseInt(input);
if (month <= 12) {
mExpiryDate.setText(mExpiryDate.getText().toString() + "/");
mExpiryDate.setSelection(mExpiryDate.getText().toString().length());
}
}else if (s.length() == 2 && mLastInput.endsWith("/")) {
int month = Integer.parseInt(input);
if (month <= 12) {
mExpiryDate.setText(mExpiryDate.getText().toString().substring(0,1));
mExpiryDate.setSelection(mExpiryDate.getText().toString().length());
} else {
mExpiryDate.setText("");
mExpiryDate.setSelection(mExpiryDate.getText().toString().length());
Toast.makeText(getApplicationContext(), "Enter a valid month", Toast.LENGTH_LONG).show();
}
} else if (s.length() == 1){
int month = Integer.parseInt(input);
if (month > 1) {
mExpiryDate.setText("0" + mExpiryDate.getText().toString() + "/");
mExpiryDate.setSelection(mExpiryDate.getText().toString().length());
}
}
else {
}
mLastInput = mExpiryDate.getText().toString();
return;