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.
Related
I'm trying to check the editText condition. In the code below, I declared a setOnClickListener method to check the condition of editText. If condition is true, I want to print toast message, change the activity and to output a sound. If condition fails, it should toast a single message. In both cases if it's true or not, it prints me only "Incorect" no matter if editText is correct.
What I am doing wrong?
public void next(View v){
final MediaPlayer correctSound = MediaPlayer.create(this, R.raw.correctsound);
Button playCorrectSound = (Button) this.findViewById(R.id.angry_btn1);
final EditText editTextt = (EditText) findViewById(R.id.editText);
playCorrectSound.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editTextt.setVisibility(View.INVISIBLE);
if(editTextt.getText().toString() == "string")
{
Toast.makeText(getApplicationContext(), "Correct", Toast.LENGTH_SHORT).show();
correctSound.start();
Intent i = new Intent(Hereuu.this, MainActivity.class);
startActivity(i);
} else {
Context context = getApplicationContext();
CharSequence text = "Incorect";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
editTextt.setVisibility(View.VISIBLE);
}
});
}
Like everyone had said, you
Basically, when you use == operator, your are checking if the reference for object are the same/equals. When you use .equals(String), the method checks the content.
tip:
When your are working with Strings, remember to avoid NullPointerException situations. So,you should write "constant".equals(editTextValue) instead of editTextValue.equals("constant")
The link bellow will help you to understand how String objects and String content work:
Java String.equals versus ==
regards
in java you need to compare strings using equals method instead of ==
check this topic for more details
I would suggest you to take some basic JAVA lessons. That will immensely help you.
For now, the problem is in the way you are checking equality of the strings. You do not use == with strings, you use String#equals() method. So,
Change
editTextt.getText().toString() == "string"
to
editTextt.getText().toString().equals("string")
Make sure to compare strings in java with .equals and not ==. Use this if statement:
if(editTextt.getText().toString().equals("string"){
My code:
fractionNumEt.addTextChangedListener(new TextWatcher() {
boolean ignoreChange = false;
#Override
public void afterTextChanged(Editable s) {
if(!ignoreChange) {
String string = String.valueOf(s);
if (string.length() > 2) {
string = string.substring(0, string.length() - 1);
ignoreChange = true;
fractionNumEt.setText(string);
ignoreChange = false;
}
}
}
....
I am trying to limit the characters to length 2, but want to keep listening. When I type '1','2', it displays "12" which is fine. Now when I type '3', it writes "31" instead of "23".
What on earth is going on!
I also tried:
string = string.substring(1, string.length());
in this case it works for the first time only n then nothing is changed.
This is happening because after setText(), EditText's cursor returns to first position. Then, any new number will be added at the begging of the String.
Try to update your code as follows:
#Override
public void afterTextChanged(Editable s) {
if(!ignoreChange) {
String string = String.valueOf(s);
if (string.length() > 2) {
string = string.substring(0, string.length() - 1);
ignoreChange = true;
fractionNumEt.setText(string);
fractionNumEt.setSelection(fractionNumEt.getText().length());
ignoreChange = false;
}
}
}
Just a suggestion
Check Editable Docs HERE
I think you don't need to convert it to String. afterTextChanged(Editable s) receives a Editable as argument. You can change it directly. Don't need to covert it to a String.
Moreover: You don't even need to make EditText.setText() because any change in the editable, will be passed automatically to EditText (since afterTextChanged is called by android and give you a chance to update the text few moments before to effectively display that text in the EditText).
Maybe, something like that:
#Override
public void afterTextChanged(Editable s) {
if(!ignoreChange) {
if(s.length() > 2) {
s.delete(s.length() - 1,s.length());
}
}
}
Play a little bit with Editable and you will see that it is easier.
Scenario: when the focus is lost from an EditText, I'm checking if it contains null (in the first if block).
If so, then I'll show a Toast.
In the else-if block I'm checking if the EditText doesn't contain letters.
Then I'll show a toast, but when I run the application, the Toast is shown even on a correct input.
I.e.: If I enter any letter the Toast should not be shown, it should be shown only when a null or digit/special symbol is entered.
Here is the code
et1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(!hasFocus)
{
a = et1.getText().toString();
if (a.equals(""))
{
Toast.makeText(getApplicationContext(), "Your entry is incorrect!!", Toast.LENGTH_LONG).show();
}
else if (!a.contains("[a-z]")||!a.contains("[A-Z]")) {
Toast.makeText(getApplicationContext(), "Your entry is incorrect!!", Toast.LENGTH_LONG).show();
}
else
{
}
Please help
The '==' operator only compares references. To compare string values you must use the equals() method.
Instead of
if (a == "")
use
if (a.equals(""))
See: What is the difference between == vs equals() in Java?
It's not working because:
if (a == "")
won't work in Java
Use
if (a.equals(""))
instead
Also, String.contains doesn't use regular expressions, but CharacterSequences.
So, unless your string doesn't contain the exact character sequences "[a-z]" or "[A-Z]" (and only one of these 2 strings), you'll never get a match.
See: http://developer.android.com/reference/java/lang/String.html#contains(java.lang.CharSequence)
The problem is:
if (a == "")
Strings can't be compared like this. Instead, check for size equal to 0, or against a specific string with the equals() method.
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
}
}
}
}
i need a favor.. i'm confused to put these codes to check whether the edittext is empty or not:
String input = editText.getText().toString();
if(input == null || input.trim().equals("")){
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
}
where must i write these codes? is it between these codes?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menuawal);
...
...
...
JmlAhliWarisAnakLK = (EditText) findViewById(R.id.JmlAhliWarisAnakLK);
JmlAhliWarisAnakPR = (EditText)findViewById(R.id.JmlAhliWarisAnakPR);
or in this function after double sisa=0;??
public void cc() {
int JmlWarisAnakPR = Integer.parseInt(JmlAhliWarisAnakPR.getText().toString());
int JmlWarisAnakLK = Integer.parseInt(JmlAhliWarisAnakLK.getText().toString());
int JmlHarta = Integer.parseInt(JmlHartaPeninggalan.getText().toString());
double HasilSuami = 0;
double HasilIstri = 0;
double HasilAnakLK = 0;
double HasilAnakPR = 0;
double sisa = 0;
}
please correct me if i'm wrong.. :D
you are on the right track
After you set the layout using setContentView you need to add your EditText's which you are doing fine as follows.
JmlAhliWarisAnakLK = (EditText)findViewById(R.id.JmlAhliWarisAnakLK);
JmlAhliWarisAnakPR = (EditText)findViewById(R.id.JmlAhliWarisAnakPR);
You then need to store the value you get from the EditText's in some variable,
int JmlWarisAnakPR = Integer.parseInt(JmlAhliWarisAnakPR.getText().toString());
....
....
After you have stored your values you can then call some method that validates your input on click of a button(if you have):
public void validateinput()
{
if(input == null || input.trim().equals(""))
{
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
}
}
According to me, you should put the check on some event, like if its login screen, then on click of submit button. or other wise on focus change it main instantly provide user with the toast that he left the field empty. or if other case, please provide more information for your query. thanks.
That depends on when you want to validate the editText..You propably have some button which "submits" the EditText so call this code in after onClick event gets fired on the button..
Put the input validation code when you have to navigate away from the current activity, either to go to another activity or to save the input details. That's the least annoying place to shove an error message onto the user.
Another approach is to validate when the focus leaves the EditText. But in this case the error notification should be more subtle (and therefore less annoying) like changing the EditText's background to lightred.
Ur questions does not seem to be clear. Are u asking where do u need to put the validation for empty edittext? If this is ur question then the general case would be to validate during any events such as BUTTON CLICK. Set the onClickListener for ur button and inside ur onclick perform the validation.
String input = editText.getText().toString();
if(input == null || input.trim().equals("")){
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
}
Your above code is pretty much correct. You Must need to add above code whenever you want to take input from these edittext, Or whenever you want to save these value. make a function which will return true if edit text is empty so u can ask user to enter values
public boolean isETEmpty(){
String input = editText.getText().toString();
if(input == null || input.trim().equals("")){
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
return true;
}
return false; // if not empty
}
call this function Whenever u want to use values from ET, if this function return true, you must let user enter values. Such as on Button Click to save etc