I am trying to get a message to appear when a button is clicked to tell the user to fill in the blank field. Currently, if the field is blank, it crashes/force closes the app. I tried to do the following code and had zero success. Originally I didn't have the if/else in there, I just ran the calculator(); method and the following imm code.
Could someone point me into the right direction?
public void onClick(View v)
{
if ((EditText)findViewById(R.id.amount1)== null)
{
Context context = getApplicationContext();
CharSequence text = "Enter a number";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else
{
calculator();
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
Im pretty sure this is the bad code:
if ((EditText)findViewById(R.id.amount1)== null)
Just dont know how to word it the way I want.
Try checking the length of the text in the EditText widget
EditText e = (EditText)findViewById(R.id.amount1));
if(e.getText().length == 0){
//Show Toast
}else{
//continue your code
}
Use this code.
EditText et = (EditText)findViewById(R.id.amount1));
if(et1.getText().length() == 0){
//Display toast here
} else{
//Your code
}
EditText text = (EditText)findViewById(R.id.amount1);
if(TextUtils.isEmpty(text.toString())) {
// show toast
}
Even if the field is blank, the edittext is not null. Use:
EditText editText = (EditText)findViewById(R.id.amount1);
String text = new String(editText.getText());
if (test.equals("")) {
//...
((EditText)findViewById(R.id.amount1)== null is just getting a reference to the EditText with the id amount1, it is not checking to see if that EditText has a valid entry.
To see if the EditText has text, you can get the String it holds by via EditText#getText().toString()
To make this work, first store the reference to the EditText in a var, then perform your checks on the String:
EditText et = (EditText)findViewById(R.id.amount1);
String amount1 = et.getText().toString();
if (amount1.equals("")) {
// Do your stuff here
}
I'm using local variables and just assuming you want the string to have content. You will likely need to do other checks to handle all the cases (like malformed input). Some of this you can reduce by setting the inputType on the EditText. For example, you might set it to numberDecimal if you are trying to handle only decimal numbers.
You actually want to check if the contents of the EditText are null or an empty string.
The line in question should look something like this:
if("".equals(((EditText)findViewById(R.id.amount1)).getText().toString()))
Of course you may want to break that statement up into more lines to make it a bit more readable!
Related
i am working in a app that triggers local notification. for that i have coded to display a date in Edittext, such that when a user clicks on edit text, a date picker dialog opens.
In a case, if edittext is null, i have to show a error to the user and i have coded the below for that.
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (et_reminderDate.getText().toString().trim().length() == 0) {
et_reminderDate.requestFocus();
et_reminderDate.setError(getResources().getString(R.string.reminder_selectDate));
} else if (et_reminderTime.getText().toString().trim().length() == 0) {
et_reminderTime.requestFocus();
et_reminderTime.setError(getResources().getString(R.string.reminder_time));
} else if (et_dateDue.getText().toString().toString().length() != 0) {
et_dateDue.setError(null);
et_dateDue.clearFocus();
} else if (et_reminderDate.getText().toString().toString().length() != 0) {
et_reminderDate.setError(null);
et_reminderDate.clearFocus();
}else{
My project coding goes here!
}
}
But i am just getting the error icon. The error text is not shown.
As of my assumption, i have validated for text in edittext. Is that i have to validate for date in Edittext to find whether the date is null?
Note: In the same code, i am getting error message for edittext with text values. For example, edittext where user can enter name. Only for
Edittext with date picker i am not getting the error message!
Any help thanks!
To show date picker on single click you must have set android:focusable="true" on EditText so either remove android:focusable="true" or make it android:focusable="false" and you are done.
Try this code
if (et_reminderTime.getText().toString().trim().isEmpty()) {
et_reminderTime.setError(getResources().getString(R.string.reminder_time));
et_reminderTime.requestFocus();
} else if(et_dateDue.getText().toString().toString().length()!=0) {
//remove the request focus for et_dateDue
et_dateDue.setError(null);
}
So try this, i actually use TextInputLayout and TextInputEditText and never had problems
EditText.setError doesnt show Error text and only shows icon
Altough I cannot see the full code, I assume the problem is with else ifstatement.
I think they should be handled as seperate if statements.
Like this:
if (et_reminderTime.getText().toString().trim().length() == 0) {
et_reminderTime.requestFocus();
et_reminderTime.setError(getResources().getString(R.string.reminder_time));
}
if(et_dateDue.getText().toString().length()!=0) {
et_dateDue.requestFocus();
et_dateDue.setError(null);
}
I have an EditText and a Button.
I want if an EditText was empty when clicked on my Button. I want to show message as a toast, like "please enter a number".
You can do something like this:
boolean hasValue = editText.getText().length() > 0;
or
boolean hasValue = !editText.getText().toString().isEmpty();
or to make sure it doesn't contain only spaces:
boolean hasValue = !editText.getText().toString().trim().isEmpty();
The cleanest way to do this is TextUtils.isEmpty(editText.getText())
The reason I say this is the cleanest way is because:
You avoid pointless conversion between CharSequence and String. Which creates an object. editText.getText() returns Editable, calling toString() creates an additional object which is not good. This method will also never return null in my experience.
You get a null and a length check out of that. If you look at the code for TextUtils.isEmpty(), it basically checks if the CharSequence is null and length is zero.
It avoids code duplication and the same method can be used with Strings or CharSequence objects and Editable is an implementation of CharSequence.
It's provided as part of the Android framework.
If you want to check the length of the trimmed String. Then use:
TextUtils.isEmpty(editText.getText())
&& TextUtils.getTrimmedLength(editText.getText()) == 0
If you want, you can create your own utility method to do this so you don't have to add such a long condition in your code repeatedly.
I would attached an OnFocusChangeListener to your EditText to check the change in value or a TextWatcher or both depending on how critical your requirement is. If your field had focus and lost it, do your validation with the OnFocusChangeListener, if your field has focus and the user is typing and delete the content or the content is too short, use TextWatcher to let them know.
Use this on click of your button:
EditText editText = (EditText) view.findViewById(EditTextID);
if(editText.getText().toString().length()==0) {
Toast alert = Toast.makeText(context, toast_message, Toast.LENGTH_SHORT);
alert.show();
}
In the onClickListener() of the button:
int length = editText.getText().length();
if(length == 0)
{
Toast.makeText(getActivity(), "Please enter a number",Toast.LENGTH_LONG).show();
}
you probably already found your answer, but for the ones who came here hoping to find an answer here is how its done:
you have to make a String object or Int object first then in your button function Click write this:
#Override
public void onClick(View view) {
String numberValue;
numberValue = yourEditText.getText().toString();
if (emailEtValue.matches("")){
Snackbar sbEmptyValue = Snackbar.make(view, "You must enter an Integer Value", Snackbar.LENGTH_LONG);
sbEmptyValue.show();
} else {
//DO THE THING YOU WANT
}
}
you can also use Toast but i prefer Snackbar because its cooler than Toast.
I use setError() to show validation errors. In one case, the field is close to the left side of the screen, when the error message showed up, it visually pointed to the wrong EditText field - instead of pointing to the field showing 1234, it should really point to the blank field on the left, see attached screenshot. Does anyone know a solution to this? Thanks!
The screenshot was taken on a Galaxy 3 phone running Android 4.4.2.
I got one workaround, add \n to format the message and reduce the width of each line:
text1.setError("this field must\nbe 1 character\nin length");
This is the solution for your problem..
Try this..
EditText edt1=(EditText) findViewById(R.id.editText2);
EditText edt2=(EditText) findViewById(R.id.editText3);
EditText edt3=(EditText) findViewById(R.id.editText1);
// Reset errors.
edt1.setError(null);
edt2.setError(null);
edt3.setError(null);
String txt3 = edt3.getText().toString().trim();
String txt1 = edt1.getText().toString().trim();
String txt2=edt2.getText().toString().trim();
boolean cancel = false;
View focusView = null;
if (TextUtils.isEmpty(txt3)) {
edt3.setError(getString(R.string.error_field_required));
focusView = edt3;
cancel = true;
}
if (TextUtils.isEmpty(txt2)) {
edt2.setError(getString(R.string.error_field_required));
focusView = edt2;
cancel = true;
}
if (TextUtils.isEmpty(txt1)) {
edt1.setError(getString(R.string.error_field_required));
focusView = edt1;
cancel = true;
}
if (cancel) {
focusView.requestFocus();
} else {
//do the operations you want do here
}
I have a quick question.
I have a screen with some numbers, when you click one of the numbers, the number gets appended to the end of the edittext.
input.append(number);
I also have a backbutton, when the user clicks this button I want to remove the last character.
At the moment I have the following :
Editable currentText = input.getText();
if (currentText.length() > 0) {
currentText.delete(currentText.length() - 1,
currentText.length());
input.setText(currentText);
}
Is there an easier way to do this ? Something in the line of input.remove()?
I realise this is an old question but it's still valid. If you trim the text yourself, the cursor will be reset to the start when you setText(). So instead (as mentioned by njzk2), send a fake delete key event and let the platform handle it for you...
//get a reference to both your backButton and editText field
EditText editText = (EditText) layout.findViewById(R.id.text);
ImageButton backButton = (ImageButton) layout.findViewById(R.id.back_button);
//then get a BaseInputConnection associated with the editText field
BaseInputConnection textFieldInputConnection = new BaseInputConnection(editText, true);
//then in the onClick listener for the backButton, send the fake delete key
backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textFieldInputConnection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
}
});
try this out,
String str = yourEditText.getText().toString().trim();
if(str.length()!=0){
str = str.substring( 0, str.length() - 1 );
yourEditText.setText ( str );
}
i have a EditText in android in which i want the user to enter the text and checks for the condition "BYE"
Code sample:
EditText text = (EditText)findViewById(R.id.EditText01);
String abc= text .getText().toString();
while( !(abc).equals("bye")){
abc = text.getText().toString();//user should enter the text from keyboard and the while loop should go and chech the condition.but not able to enter the text
//do some operation with abc
}
How can i make user to enter the text??The UI should wait for the text to be entered(something like we have InputStreamReader in java applications).
Very Simple:-
EditText text = (EditText)findViewById(R.id.EditText01);
String str = text.getText().toString();
now in str u will get string which is entered in EditText
I don't think you need a loop to do this. From your comment it looks like you also have an "Enter" button or something that you click to do the checking. Just set an onclicklistener and onclick you can make the edittext invisible (or un-editable), check is the edittext is equal to "BYE" and then do your actions might look something like this:
final EditText ET = (EditText) findViewById(R.id.EnterText);
Button B1 = (Button) findViewById(R.id.EnterButton);
B1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ET.setVisibility(View.INVISIBLE);
if(ET.getText().toString() == "BYE")
{
//do something if it is "BYE"
} else {
Context context = getApplicationContext();
CharSequence text = "Please enter BYE";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
ET.setVisibility(View.VISIBLE);
} });
Instead of running this check in an infinite loop, only run it on every onKeyUp of the EditText. You know, anyway, that the condition will only ever be fulfilled if the user actually enters something.