EditText setError message does not clear after input - android

Ok so I only have a EditText field and a button, which when pressed triggers an AsyncTask.
EditText playerName = (EditText)findViewById(R.id.playerEditText);
if(playerName.getText().toString().length() == 0 )
playerName.setError("Player name is required!");
else {
// do async task
}
The problem is that the error message seems to stay up even after when I input valid text to search. Is there a way to remove the error as soon as the EditText is not empty?

In your else bracket, put playerName.setError(null), which will clear the error.

API documentation: "The icon and error message will be reset to null when any key events cause changes to the TextView's text."
Though it is not so - and therefore we can regard this as bug.
If you use inputType such as textNoSuggestions, textEmailAddress, textPassword, the error is unset after a character is typed. Nearly as documented but again not exactly - when you delete a character, error stays.
It seems, a simple workaround with addTextChangedListener and setError(null) can attain promised behavior.
Besides there are posts about icon losing on Android 4.2. So use with care.

Try this listener:
playerName.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable edt){
if( playerName.getText().length()>0)
{
playerName.setError(null);
}
}

If you want to hide the error message one way is you apply onclicklistener on the edit box and then
editTextName.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
editTextName.setError(Null)
}
});

Below code worked for me
#OnTextChanged(
value = R.id.editTextName,
callback = OnTextChanged.Callback.TEXT_CHANGED)
public void afterInput(CharSequence sequence) {
editTextName.setError(null);
editTextName.setErrorEnabled(false);
}
'
editTextName.setError(null) Will clear the error message.
editTextName.setErrorEnabled(false) Will remove additional padding.

Add a TextWatcher to your EditText and onError, show your error message using et.setError(errorMessage) else you can remove the error message and error icon like below.
// to remove the error message in your EditText
et.setError(null);
// to remove the error icon from EditText.
et.setCompoundDrawables(null, null, null, null);

This code worked for me.
textInputSetting(binding.emailEdt)
fun textInputSetting(view: TextInputLayout) {
view.apply {
this.editText!!.addTextChangedListener {
if (this.editText!!.text.isNotEmpty()) {
this.error = null
this.isErrorEnabled = false
}
}
}
}

Related

how to save Editable s value in afterTextChanged?

I am going to save the value in one textview after the length of input string is fulfilled. but saved value is empty if the value of textview is used. If Editable s value in afterTextChanged is used, it causes crash.
Some codes as following:
number = (EditText) findViewById(R.id.number);
final String numberStr = number.getText().toString();
if following afterTextChanged is used, empty value is saved even I already input sth.
#Override
public void afterTextChanged(Editable s) {
if (s.length() == 11) {
Toast.makeText(MainActivity.this, numberStr , Toast.LENGTH_SHORT).show();
saveSettingNote(MainActivity.this, "number_save", "number", numberStr);
number.setText(getSettingNote(MainActivity.this,"number_save", "number"));
}
}
if following code is used, it will cause crash:
#Override
public void afterTextChanged(Editable s) {
if (s.length() == 11) {
Toast.makeText(MainActivity.this, s.toString(), Toast.LENGTH_SHORT).show();
saveSettingNote(MainActivity.this, "number_save", "number", s.toString());
number.setText(getSettingNote(MainActivity.this,"number_save", "number"));
}
}
Saving and getting are based on SharedPreferences, which works well in other situation.
Actually, what I want to implement is saving String after the criteria is fulfilled for input string.
Please help to identify what is wrong in above code or suggest a new to get that function. Thanks a lot in advance.
Your app is crashing because your listener is looping indefinitely with the same value passed in over and over.
The ugly truth is that you've to unbind your listener, set the value and then bind it again:
#Override
public void afterTextChanged(Editable s) {
if (s.length() == 11) {
// unbind your listener
editText.addTextChangedListener(null);
// do your stuff
Toast.makeText(MainActivity.this, s.toString(), Toast.LENGTH_SHORT).show();
saveSettingNote(MainActivity.this, "number_save", "number", s.toString());
number.setText(getSettingNote(MainActivity.this,"number_save", "number"));
// bind your listener again
editText.addTextChangedListener(MainActivity.this);
}
}
Using RxBinding you can achieve this in a more elegant way:
RxTextView.textChanges(editText)
.map { it.toString() }
.filter({ it.length == 11 })
.distinctUntilChanged() // <-- the important part
.subscribe(
{ s -> /* do your stuff here */}
)
you set text in editext afterTextChanged(Editable s) which calls text change listener again and again and cause the application to crash. call number.setText(getSettingNote(MainActivity.this,"number_save", "number")); outside the text change listener.
My guess it that by declaring numberStr as you did, you expect to change its value each time the edit text change its content. However, this is not the case; it will be initialised with an empty string "" (unless you don't have any other string in the edit text at that moment) and then it will NEVER change its value, thus resulting in the empty value that you save. As solution I would suggest to make numberStr non final and update its value (like you already did) each time before showing the Toast.

SetError on EditText

I am working on an android app. I am having an EditText on which I have applied OnCllickListener().
EditText _input = new EditText(context);
_input.setSingleLine(true);
_input.setFocusable(false);
I am setting OnClickListener() on this EditText:
_input.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// OnClick work here
}
});
I have applied some validations on this field and calling setError() method on this EditText. It shows that red icon of error in the EditTextwhen the validation fails. But when I click on that error icon it executes the OnClickListener() on this EditTextand I am not able to see the error occurred.
Is there any other way to do so, so that I can handle both functions.
Thanks a lot in advanced !!!
You would check if currently the edit text is in an error state, within the onclick handler:
_input.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (view.getError() == null) {
// do not handle the click
return;
}
}
});
You can check for an error like like this:
if(view.getError() == null) return;
See the doc here
getError()
Returns the error message that was set to be displayed with
setError(CharSequence), or null if no error was set or if it the error
was cleared by the widget after user input.
Source
I have solved this with a simple solution. Just set text of editText to empty string before setting error and error message will show again like without onClickListener.

Check textfield is empty in Android Studio

I am trying to check whether my textfield is empty for validation purpose but i am getting an error message cannot resolve method isEmpty
This is my partial coding:
private void addMovie(){
DatabaseHandler databaseHandler = new DatabaseHandler(getApplicationContext());
if(getIntent().getExtras()== null){
databaseHandler.insertRow(
mvidEditText.getText().toString(),
mvtitleEditText.getText().toString(),
mvtypeEditText.getText().toString(),
mvstoryEditText.getText().toString(),
mvratingEditText.getText().toString(),
mvlanguageEditText.getText().toString(),
Integer.parseInt(mvruntimeEditText.getText().toString()));
if (mvidEditText.isEmpty() || mvtitleEditText.matc) {
Toast.makeText(this, "You did not enter a username", Toast.LENGTH_SHORT).show();
return;
}
}else {
databaseHandler.updateRow(rowID,
mvidEditText.getText().toString(),
mvtitleEditText.getText().toString(),
mvtypeEditText.getText().toString(),
mvstoryEditText.getText().toString(),
mvratingEditText.getText().toString(),
mvlanguageEditText.getText().toString(),
Integer.parseInt(mvruntimeEditText.getText().toString()));
}
}
Are there any ways to do this? I did some research from stack overflow too.Thank you.
Now in new version getText() is not working directly so use only text
like this
if (enter_name.text.toString().isEmpty()) {
}
As far as my knowledge goes, there is no method isEmpty() in EditText class. you should do like this-
if(!TextUtils.isEmpty(editTextRef.getText().toString())){
///.... your remaining code if the edittext is not empty
}
if(mvidEditText.getText().length() == 0){}
you can try following for checking empty value for edittext
mvidEditText.getText().toString().isEmpty();
where isEmpty returns true if length of this string is 0.
if(mvidEditText.getText().toString().equals("")){print message here}
to check Edittext is empty
if(myeditText.getText().toString().trim().length() == 0)
Or use below function
private boolean isEmpty(EditText editText) {
return editText.getText().toString().trim().length() == 0;
}

Check if is it empty on edit text is not working

What i have is android app , and in one of activities i have two edit text with button, and i want either if one of them were empty when i click the button to preform a toast to tell the user to enter data, and if it was not empty i want it to open intent and do other thing , here is my code :
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(quantity.getText()==null){
Toast.makeText(FullImageActivity2.this,"please enter quantity",Toast.LENGTH_LONG).show();
}
else if(extra.getText()==null){
Toast.makeText(FullImageActivity2.this,"please enter extra",Toast.LENGTH_LONG).show();
}
else{
Quan=quantity.getText().toString();
name=itemId;
image=R.drawable.products;
Intent cart=new Intent(FullImageActivity2.this,CartList.class);
cart.putExtra("name", name);
cart.putExtra("quantity",Quan);
cart.putExtra("image", image);
Log.e("quan",Quan+"");
Log.e("name",name+"");
startActivity(cart);
}
}
});
But the weird thing that if they were empty , else is working !! which is not logic at all .. the validation on empty text is not empty , Why this is happening?? Help plz
Try to used .equals() method
if(quantity.getText().toString().trim().equals(""))
Try
if(editText.getText().toString().length()<1){
//do something
}
And of course you are mistaking null with "" which means no string but not null.
When Edittext is empty, getText() method returns empty string, not null.
Try:
if(quantity.getText().toString().equals("")){
Of course, if you want to avoid entering only spaces, use
if(quantity.getText().toString().trim().equals("")){

Setting initial Edittext value to blank on focus

I have 4 edit text fields in my app which take in one long and 3 double values respectively. I have used them with onFocusChangedListener(). My issue is whenever a certain edit text gains focus a default (0.0 in case of double) is displayed into the edit field before the user enters the values. I want them to to be blank before the user enters his values. I have tried using editText.setText("") and editText.setHint(""). But these work when the activity starts, but once the edit field gains focus the default values are shown.
Please help me with the glitches.
Thank you.
Heres the code
public void onFocusChange(View EditTextFocus , boolean hasFocus)
{
// TODO Auto-generated method stub
try
{
km= Long.parseLong(ETKm.getText().toString());
fuelQty= Double.parseDouble(ETFuelQty.getText().toString());
fuelPrice= Double.parseDouble(ETFuelPrice.getText().toString());
totalCost= Double.parseDouble(ETTotalCost.getText().toString());
}
catch(NumberFormatException ne)
{
ne.printStackTrace();
}
if(ETTotalCost.hasFocus())
{
if((fuelQty!=0)&&(fuelPrice!=0))
totalCost=fuelQty*fuelPrice;
ETTotalCost.setText(new DecimalFormat("##.##").format(totalCost));
}
else if(ETFuelQty.hasFocus())
{
ETFuelQty.setText("");
if((fuelPrice!=0)&&(totalCost!=0))
fuelQty= (int) (totalCost/fuelPrice);
ETFuelQty.setText(String.valueOf(fuelQty));
}
else if(ETFuelPrice.hasFocus())
{
ETFuelPrice.setText("");
if((fuelQty!=0)&&(totalCost!=0))
fuelPrice=totalCost/fuelQty;
ETFuelPrice.setText(String.valueOf(fuelPrice));
}
}
Try setting setHint() to something.
A hint is a placeholder until the person enters some input, so you can put something like "Fuel price".
I solved my problem. It might prove useful for others searching this as well.
My issue was that I was initializing and parsing my variables before they came in focus. This made me get the initial values ie. null (0) values in the edit fields when in focus.
I initialized and parsed my variables after the edit fields gained focus
So, I changed my code to:
*case R.id.ETTotalCost:
if(ETTotalCost.hasFocus())
{
if(ETFuelQty.length()>0 && ETFuelPrice.length()>0)
{
fuelQty=Double.parseDouble(ETFuelQty.getText().toString());
fuelPrice= Double.parseDouble(ETFuelPrice.getText().toString());
if((fuelQty!=0)&&(fuelPrice!=0))
totalCost=fuelQty*fuelPrice;
ETTotalCost.setText(new DecimalFormat("##.##").format(totalCost));
}
}*

Categories

Resources