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("")){
Related
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.
I am currently developing my first android application, which is actually my first contact with java ever. Therefore, I suppose this question has an obvious answer to experienced developers, but I couldn't find anything at SO or anywhere else. The following EditText has two toasts (I'm not sure if that sounded right). One is shown if the user types a specific word (in this case, Please is shown if the user types Magic word and presses the button). I would like the another toast to appear if the user types anything else but that word (anything but "Magic word") when clicking the button.
EditText editText1 = (EditText) findViewById(R.id.editText1);
{
if(editText1.getText().toString().trim().equals("Magic word"))
{
Toast.makeText(MainActivity.this,
"Please", Toast.LENGTH_LONG).show();
}
}
else if (editText1.getText().toString().trim().equals())
{
Toast.makeText(MainActivity.this,
"You didn't say the magic word", Toast.LENGTH_LONG).show();
}
}
}
});
I apologize for my poor english. Hopefully, I made myself understood.
Thank you very much.
Following code give you the solution:
final EditText editText1=(EditText)findViewById(R.id.editText1);
Button btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
final String edittext=editText1.getText().toString();
if(edittext.trim().equals("Magic word"))
{
Toast.makeText(MainActivity.this,
"Please", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(MainActivity.this,
"You didn't say the magic word", Toast.LENGTH_LONG).show();
}
}
});
More simple way!!
String hello = editText1.getText().toString();
and then,
Toast.makeText(MainActivity.this, "The text is" +hello , Toast.LENGTH_SHORT).show();
More accurately "Magic word" isn't a word, its two with a space. The first if statement will require the text in the EditText to be exactly that for the statement to be true. If you actually intended for "magic word" to merely be somewhere in the text typed into the EditText to show a Toast that says please, look into using String.contains() or regex for the first comparison.
For all other conditions there's no need to check the value of the EditText. In other words remove the second if just keep else as Luksprog mentioned.
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
I want to make that when the user click the button below and the String on EditText is empty, it shows a dialog.
So I made this method, but unfortunately rather than showing a Dialog Box, the app crashed. There's no problem with the Dialog box method, the problem is the IF function doesn't read what I requested properly.
Anybody has the solution for this?
Here's my method:
public void onClick(View v) {
if(v == launchSimplePayment) {
String amount = paymentAmount.getText().toString();
System.out.println(amount);
if (amount == "")
{
errorDialog();
}
else
{
System.out.println(amount);
// Use our helper function to create the simple payment.
PayPalPayment payment = exampleSimplePayment();
// Use checkout to create our Intent.
Intent checkoutIntent = PayPal.getInstance().checkout(payment, this, new ResultDelegate());
// Use the android's startActivityForResult() and pass in our Intent. This will start the library.
startActivityForResult(checkoutIntent, request);
}
}
Change this
if (amount == "")
with this
if (amount.equals(""))
Remember that the operator == compares references, not the content!
You should rewrite the condition like this:
if (amount.trim().equals(""))
Since a blank space like this " " would pass over your validation check.