How to hide EditText error after typing on textfield? - java

Here I first attempt to login with blank values and it successfully displayed the errors. Now I am looking to hide the error "email required" when I type a value to the email textfield. I want to remove the error message "email required" when I type the first key in the email textfield
. How can I implement such a feature to this code?
textInputEmail = (TextInputLayout) findViewById(R.id.text_input_email);
textInputPassword = (TextInputLayout) findViewById(R.id.text_input_password);
login =(Button) findViewById(R.id.loginBtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!ValidateEmail() || !ValidatePassword())
{
return;
}
String inputs = "Email : "+ textInputEmail.getEditText().getText().toString().trim();
inputs +="\n";
inputs +="Password : "+ textInputPassword.getEditText().getText();
Toast.makeText(MainActivity.this,inputs, Toast.LENGTH_SHORT).show();
}
});
}
private Boolean ValidateEmail() {
String emailPattern = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
String emailInput = textInputEmail.getEditText().getText().toString().trim();
if (emailInput.isEmpty()) {
textInputEmail.setError("Email required");
return false;
} else if (!emailInput.matches(emailPattern)) {
textInputEmail.setError("Invalid Email");
return false;
} else {
textInputEmail.setError(null);
textInputEmail.setErrorEnabled(false);
return true;
}
}

You can use TextWatcher to when text is changed remove the error
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
textInputEmail.setError(null);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
}
});

just set error text to empty string
editText.setError("", null);

You have to add text watcher for edit text. Then you hide Required error.
Check below example for better understanding.
<android.support.design.widget.TextInputLayout
android:id="#+id/text_input_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/Theme.AppCompat">
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword"
android:padding="12dp">
</android.support.design.widget.TextInputLayout>
Then in your activity/fragment
private EditText passwordEditText;
private TextInputPassword textInputPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Initializing views */
passwordEditText = (EditText) findViewById(R.id.password);
/* Set Text Watcher listener */
passwordEditText.addTextChangedListener(passwordWatcher);
textInputPassword = (TextInputLayout)
findViewById(R.id.text_input_password);
}
private final TextWatcher passwordWatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void afterTextChanged(Editable s) {
if (s.length() == 0) {
textInputPassword.setErrorEnabled(true);
textInputPassword.setError("Password Required");
} else{
textInputPassword.setErrorEnabled(false);
textView.setText("You have entered : " + passwordEditText.getText());
}
}
};

You could control the visibility of the error like. I'm asuming you can get the reference to the error label and it's stored in a variable called errorLabel
#Override
public void onClick(View v) {
errorLabel.setVisibility( validateEmail() && validatePassword() );
}

Related

Hide Keyboard automatically when Edit-text max length reached to it's limit

I was creating user interface where user have to enter the mobile number in EditText. maxLength of that EditText is 10. Now I want when 10 digits entered by the user the keyboard automatically get hide. How to implement this. I already searched on google but not a single code worked for me. Below is my XML & Fragment code.
XML Code
<EditText
android:id="#+id/editTextPhone"
style="#style/EditText"
android:background="#drawable/border_design"
android:inputType="phone"
android:hint="#string/editText_phone_hint"
android:maxLength="10"
android:drawableLeft="#drawable/phone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Fragment Code
public class MobileNumberFragment extends Fragment {
String mobileNumber;
editTextNumber = (EditText) view.findViewById(R.id.editTextPhone);
protected boolean isValidNumber(String registerMobileNumber) {
if (registerMobileNumber != null && registerMobileNumber.length() == 10) {
return true;
}
return false;
}
private void SendOtp() {
mobileNumber = editTextNumber.getText().toString().trim();
if (!isValidNumber(mobileNumber)) //Condition so that no edit-text will remain empty
{
editTextNumber.setError("Enter the Valid Mobile Number");
editTextNumber.requestFocus();
return;
} else {
buttonSendOtp.setText("Processing...");
}
}
You can force Android to hide the virtual keyboard using the InputMethodManager, calling hideSoftInputFromWindow, passing in the token of the window containing your focused view.
// Check if no view has focus:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtName = (EditText)findViewById(R.id.txtName);
txtName.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if(s.toString().length() == 10){
HideKeyboardFormUser();
}
}
});
}
public void HideKeyboardFormUser(){
View view = getCurrentFocus();
InputMethodManager hideKeyboard = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
hideKeyboard.hideSoftInputFromWindow( view.getWindowToken(), 0);
}
}
This will force the keyboard to be hidden in all situations. In some cases you will want to pass in InputMethodManager.HIDE_IMPLICIT_ONLY as the second parameter to ensure you only hide the keyboard when the user didn't explicitly force it to appear (by holding down menu).
editTextNumber.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (s.toString().length() >= 10) {
editTextNumber.setVisibility(View.GONE);
} else {
editTextNumber.setVisibility(View.VISIBLE);
}
}
});
You need to add a TextWatcher listener to the EditText, and hide the keyboard once the length reached 10.
editTextNumber = (EditText) view.findViewById(R.id.editTextPhone);
editTextNumber.addTextChangedListener(new TextWatcher() {
#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.length() == 10){
hideSoftKeyboard(requireActivity());
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
public void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
View currentFocus = activity.getCurrentFocus();
if (inputMethodManager != null) {
IBinder windowToken = activity.getWindow().getDecorView().getRootView().getWindowToken();
inputMethodManager.hideSoftInputFromWindow(windowToken, 0);
inputMethodManager.hideSoftInputFromWindow(windowToken, InputMethodManager.HIDE_NOT_ALWAYS);
if (currentFocus != null) {
inputMethodManager.hideSoftInputFromWindow(currentFocus.getWindowToken(), 0);
}
}
}

How to disable button with multiple edit text using Textwatcher?

I am trying to disable my button if my input edit texts are empty. I am using text watcher for this. To test it out , i have only tried with only two edit texts to start.
However, my button stays enabled no matter what.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_profile);
fnameInput = findViewById(R.id.et_firstname);
lnameInput = findViewById(R.id.et_lastname);
numberInput = findViewById(R.id.et_phone);
emailInput = findViewById(R.id.et_email);
nextBtn = findViewById(R.id.btn_next);
fnameInput.addTextChangedListener(loginTextWatcher);
lnameInput.addTextChangedListener(loginTextWatcher);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchNextActivity();
}
});
}
Text watcher method
private TextWatcher loginTextWatcher = new TextWatcher() {
#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 firstNameInput =firstNameInput.getText().toString().trim();
String lastNameInput = lastNameInput.getText().toString().trim();
// tried doing it this way
nextBtn.setEnabled(!firstNameInput.isEmpty() && !lastNameInput.isEmpty());
//What i've also tried
if(firstNameInput.length()> 0 &&
lastNameInput.length()>0){
nextBtn.setEnabled(true);
} else{
nextBtn.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
I expect the button to be disabled if one or all inputs are empty and enabled when all input fields are filled out.
create a method check all condition there like
private void checkTheConditions(){
if(condition1 && condition2)
nextBtn.setEnabled(true)
else
nextBtn.setEnabled(false)
}
call this method from afterTextChanged(Editable s) method
Let us consider this case for 2 EditTexts only as for now.
define 2 global CharSequence as below
CharSequence fName="";
CharSequence lName="";
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_profile);
fnameInput = findViewById(R.id.et_firstname);
lnameInput = findViewById(R.id.et_lastname);
numberInput = findViewById(R.id.et_phone);
emailInput = findViewById(R.id.et_email);
nextBtn = findViewById(R.id.btn_next);
fnameInput.addTextChangedListener(textWatcher);
lnameInput.addTextChangedListener(textWatcher2);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchNextActivity();
}
});
}
then you have to define different textwatcher for each of your Edittext
then inside each of these textWatcher assign values to CharSequence defined above
private TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
fName=s;
validate(); //method to enable or disable button (find method below)
}
#Override
public void afterTextChanged(Editable s) {
}
};
now textWatcher2
private TextWatcher textWatcher2 = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
lName=s;
validate(); //method to enable or disable button (find method below)
}
#Override
public void afterTextChanged(Editable s) {
}
};
now write validate method
void validate(){
if (fName.length()>0 && lName.length()>0){
nextBtn.setEnabled(true);
}else {
nextBtn.setEnabled(false);
}
}
Oh! You did a small mistake. Use OR condition instead of AND. So your code should be
nextBtn.setEnabled(!firstNameInput.isEmpty() || !lastNameInput.isEmpty());
And TextWatcher will only notify when you will manually change the inputs of EditText. So TextWatcher will not wark at starting. So at first in onCreate method you should manually check those EditText feilds.
Edit:
Android new DataBinding library is best suitable for this purpose.

How to disable button if ANY EditText is empty?

Ive tried using TextWatcher, but if i create multiple TextWatchers(one for each EditText), the button enables when I start filling out any of the EditText.
Example:
public class MainActivity extends AppCompatActivity {
EditText numberOneEditText;
EditText numberTwoEditText;
EditText numberThreeEditText;
TextView sumTextView;
public void calculate(View view) {
String numberOneString = numberOneEditText.getText().toString();
String numberTwoString = numberTwoEditText.getText().toString();
String numberThreeString = numberThreeEditText.getText().toString();
double numberOneDouble = Double.parseDouble(numberOneString);
double numberTwoDouble = Double.parseDouble(numberTwoString);
double numberThreeDouble = Double.parseDouble(numberThreeString);
double sum = numberOneDouble + numberTwoDouble + numberThreeDouble;
sumTextView.setText(sum.getText().toString())
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numberOneEditText = findViewById(R.id.numberOneEditText);
numberTwoEditText = findViewById(R.id.numberTwoEditText);
numberThreeEditText = findViewById(R.id.numberThreeEditText);
sumTextView = findViewById(R.id.sumTextView);
}
}
Use TextWatcher. It will solve your problem:
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.toString().trim().length()==0){
btn.setEnabled(false);
} else {
btn.setEnabled(true);
}
}
#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
}
});
This must solve your problem:
public class AppActivity extends Activity {
private EditText editText1;
private EditText editText2;
private TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
checkFieldsForEmptyValues();
}
#Override
public void afterTextChanged(Editable editable) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_activity);
editText1 = (EditText) findViewById(R.id.reg_password);
editText2 = (EditText) findViewById(R.id.reg_password2);
editText1.addTextChangedListener(textWatcher);
editText2.addTextChangedListener(textWatcher);
checkFieldsForEmptyValues();
}
private void checkFieldsForEmptyValues(){
Button btn = (Button) findViewById(R.id.btnId);
String s1 = editText1.getText().toString();
String s2 = editText2.getText().toString();
if (s1.length() > 0 && s2.length() > 0) {
btn.setEnabled(true);
} else {
btn.setEnabled(false);
}
}
}
Thanks.
Your text watcher should check that all three EditTexts have data (preferably also make sure that they are double, and display a label with an error message if otherwise)
Something like this:
TextWatcher watcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int
count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void afterTextChanged(Editable s) {
for (EditText et : new EditText[] {numberOneEditText,
numberTwoEditText, numberThreeEditText}) {
try {
Double.parseDouble(et.getText());
} catch (NumberFormatException e) {
// Disable button, show error label, etc.
button.setEnabld(false);
return;
}
}
//Enable buttton, hide error label if available
button.setEnabled(true);
}
};
}
numberOneEditText.addTextChangedListener(watcher);
numberTwoEditText.addTextChangedListener(watcher);
numberThreeEditText.addTextChangedListener(watcher);
You only have to declare one textwatcher which you assign to all edittexts. Then :
btn.setEnabled(!(str1.isEmpty || str2.isEmpty() || str3.isEmpty));
You could also directly check if it is a valid double and not enable if not.
EditText numberOneEditText;
EditText numberTwoEditText;
EditText numberThreeEditText;
TextView sumTextView;
public void calculate(View view) {
boolean isValid = true;
String numberOneString = numberOneEditText.getText().toString();
String numberTwoString = numberTwoEditText.getText().toString();
String numberThreeString = numberThreeEditText.getText().toString();
if(numberOneString.trim().isEmpty ||numberTwoString.trim().isEmpty()
|| numberThreeString.trim().isEmpty()){
isValid = false;}
if(isValid){
double numberOneDouble = Double.parseDouble(numberOneString);
double numberTwoDouble = Double.parseDouble(numberTwoString);
double numberThreeDouble = Double.parseDouble(numberThreeString);
double sum = numberOneDouble + numberTwoDouble + numberThreeDouble;
sumTextView.setText(sum.getText().toString())
}
}

EdiText crash with button.setEnabled()

I am trying to make an EditText with a listener that checks the length of the text entered. If the EditText is not empty then the button should be enabled, otherwise it is empty must be disabled. To do this I wrote this code.
final EditText editText = new EditText(context);
builder.setView(editText);
builder.setTitle("TItle");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int i) {
}
});
builder.setNegativeButton("No", null);
editText.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
AlertDialog dialog = builder.create();
dialog.show();
String text = editText.getText().toString();
if(text.trim().length()>0) {
button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
button.setEnabled(false);
}
else {
button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
button.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
Just write something in EditText crashes with a NullPointerException here: button.setEnabled(false);
Why? how can i solve?
Update
Seems like dialogo.getButton() is returning null in your case. I looked up, there is a similar issue related.
Basically you need dialogo.show() before you call getButton(). So update your code as:
builder.setNegativeButton("No", null);
final AlertDialog dialog = builder.create();
dialog.show();
editText.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
String text = editText.getText().toString();
...
...
button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
if(button != null) {
if(text.trim().length()>0) {
button.setEnabled(true);
}
else {
button.setEnabled(false);
}
}
}
...
...
Old Answer
Change your else to following:
...
...
else {
button = dialogo.getButton(AlertDialog.BUTTON_POSITIVE);
button.setEnabled(false);
}
...
...
Initially when you click on the the edit text, the addTextChangedListener will be fired and since you have not entered and text text.trim().length()=0 so the control goes to the else block.
In your else block, you are not initializing the the button, hence the NPE.
You have write the following line in else block too
button = dialogo.getButton(AlertDialog.BUTTON_POSITIVE);

Change button behaviour according to user input

I'm writing a simple app in Android.
I've encountered this problem: I've two EditText and a Button. The value of one EditText must be a multiple of the other one EditText.
When the user insert a value in the first EditText and then press the button, the other EditText should show the value calculated with the user input.
This should be possible in other verse, too.
Like a simple unit converter. When I insert value1 in EditText1 and press convert the app must show the converted value in EditText2, but if I insert a value2 in EditText2 and press convert button the app must show the converted value in EditText1.
My problem is: how can I recognize in which EditText there are last user-input?
public void convert(View view) {
EditText textInEuro = (EditText) findViewById(R.id.euroNumber);
EditText textInDollar = (EditText) findViewById(R.id.dollarNumber);
if (toDollar) {
String valueInEuro = textInEuro.getText().toString();
float numberInEuro = Float.parseFloat(valueInEuro);
// Here the conversione between the two currents
float convertedToDollar = unit * numberInEuro;
// set the relative value in dollars
textInDollar.setText(Float.toString(convertedToDollar));
}
if (toEuro) {
String valueInDollar = textInDollar.getText().toString();
float numberInDollar = Float.parseFloat(valueInDollar);
//Here the conversione between the two currents
float convertedToEuro = numberInDollar / unit;
//set the relative value in dollars
textInEuro.setText(Float.toString(convertedToEuro));
}
}
This is the code written. I've thinked to use OnClickListener..but it isn't a good idea..
You can add a TextWatcher to your two EditText in order to know which one has been updated last.
public class MainActivity extends Activity {
EditText dollar;
EditText euro;
private static final int EURO = 0;
private static final int DOLLAR = 1;
private int lastUpdated = DOLLAR;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dollar = findViewById(R.id.dollar);
euro = findViewById(R.id.euro);
dollar.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
lastUpdated = DOLLAR;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
euro.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
lastUpdated = EURO;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void convert(View view) {
switch (lastUpdated) {
case EURO:
//Do work for euro to dollar
break;
case DOLLAR:
//Do work for dollar to euro
break;
default:
break;
}
}
}
I have a different way in mind,you can try this to achieve what you want:
when user comes first on activity,let him edit any edit text fields.(one is being filled,the other will be disabled until he pressed button)
let him click button
once the results are filled and he wants to edit one of the edittext,other edittext would be automatically empty
lets say you have editText_1 and editText_2,and your button is button_1.Also take a boolean variable called convertBoolean and make it false as default.
Now,
editText_1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(convertBoolean==false){
editText_2.setEnabled(false); //disable other edittext when one is being edited
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after){
}
#Override
public void afterTextChanged(Editable s) {
String s1=editText_1.getText().toString().trim();
String s2=editText_2.getText().toString().trim();
if(!s1.equals("") && !s2.equals("") && convertBoolean==true){
//of both are filled, empty second edittext
editText_2.setText("");
convertBoolean=false;
}
if(editText_1.getText().toString().trim().equals("") && convertBoolean==false){
editText_2.setEnabled(true);
}
}
});
editText_2.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(convertBoolean==false){
editText_1.setEnabled(false); //disable other edittext when one is being edited
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after){
}
#Override
public void afterTextChanged(Editable s) {
String s1=editText_1.getText().toString().trim();
String s2=editText_2.getText().toString().trim();
if(!s1.equals("") && !s2.equals("") && convertBoolean==true){
//of both are filled, empty first edittext
editText_1.setText("");
convertBoolean=false;
}
if(editText_2.getText().toString().trim().equals("") && convertBoolean==false){
editText_1.setEnabled(true);
}
}
});
button_1.setOnClickListener(new OnClickListener(){
public void onClick(){
convertBoolean=true;
editText_1.setEnabled(true);
editText_2.setEnabled(true);
}
});

Categories

Resources