I want to check if user input is equal to the array, if not toast error message when pressing a button. I am not sure if I should check input outside the button and then use an if !equals inside button to toast the message. Here is my attempt
I have this array in strings.xml
<string-array name="people">
<item>JHON</item>
<item>MARIE</item>
<item>ALBERT</item>
<item>ALEX</item>
</string-array>
Activity.java:
String[] peopleArr =getResources().getStringArray(R.array.people);
EditText userinput=findViewById(R.id.editTextUserinput);
Button find = findViewById(R.id.findBtn);
find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = 0; i <= peopleArr.length - 1; i++) {
if (!userinput.getText().toString().equals(peopleArr[i])) {
Toast.makeText(getApplicationContext(), "Invalid user", Toast.LENGTH_SHORT).show();
}
}
}
This is wrong because it is toasting invalid user 4 times when the button is pressed.
this code check user, if can finde user will Toast: Valid User otherwise will Toast: Invalid User
String[] peopleArr =getResources().getStringArray(R.array.people);
EditText userinput=findViewById(R.id.editTextUserinput);
Button find = findViewById(R.id.findBtn);
find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Boolean userIsFounded = false;
for (int i = 0; i <= peopleArr.length - 1; i++) {
if (userinput.getText().toString().equals(peopleArr[i])) {
userIsFounded = true;
break;
}
}
String message = (userIsFounded)? "Valid User":"InValid User";
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
Related
This question already has answers here:
Set Toast Appear Length
(7 answers)
Can an Android Toast be longer than Toast.LENGTH_LONG?
(27 answers)
Closed 1 year ago.
I want to increase the duration of toast msg.I tried some code from some sites and also saw some yt videos but still the prob isn't solved.On clicking the button it displays the toast msg all at a time but i want it to display one by one on some time duration. Also I want to show toast msg that" all fields are compulsory" when even one or all edittexts are blank
public class NewUserActivity extends AppCompatActivity {
EditText name;
EditText email;
EditText phone;
EditText usname;
EditText passsword;
Button register;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_user_login);
name = (EditText) findViewById(R.id.name);
email = (EditText) findViewById(R.id.email);
phone = (EditText) findViewById(R.id.phone);
usname = (EditText) findViewById(R.id.usname);
passsword = (EditText) findViewById(R.id.passsword);
register= (Button) findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String NAME = name.getText().toString().trim();
String EMAIL = email.getText().toString().trim();
String PHONENO =phone.getText().toString().trim();
String username = usname.getText().toString().trim();
String password = passsword.getText().toString().trim();
String emailPattern = "^[a-zA-Z0-9+_.-]{3,32}+#[a-zA-Z0-9.-]{2,32}+$";
String phonePattern = "(0/91)?[7-9][0-9]{9}";
// NAME VALIDATION
if(NAME.isEmpty()){
Toast.makeText(getApplicationContext(),"Plz Enter Name",Toast.LENGTH_SHORT).show();
}else if( !((NAME.length() > 3) && (NAME.length() < 15)) ){
Toast.makeText(getApplicationContext(),"Name > 3 and < 15",Toast.LENGTH_SHORT).show();
}else if(!NAME.matches("[a-zA-Z ]+")){
Toast.makeText(getApplicationContext(),"Only enter alphabets",Toast.LENGTH_SHORT).show();
}
//EMAIL VALIDATION
if(EMAIL.isEmpty()){
Toast.makeText(getApplicationContext(),"Plz Enter Email",Toast.LENGTH_SHORT).show();
}else if(!(EMAIL.matches(emailPattern))){
Toast.makeText(getApplicationContext(),"Invalid Email",Toast.LENGTH_SHORT).show();
}
//PHONE NUMBER VALIDATION
if(PHONENO.isEmpty()){
Toast.makeText(getApplicationContext(),"Plz Enter Phone no.",Toast.LENGTH_SHORT).show();
}else if(!(PHONENO.length()==10)){
Toast.makeText(getApplicationContext(),"Invalid Phone no.",Toast.LENGTH_SHORT).show();}
else if(!(PHONENO.matches(phonePattern))){
Toast.makeText(getApplicationContext(),"Invalid Phone Number",Toast.LENGTH_SHORT).show();
}
//USERNAME VALIDATION
if(username.isEmpty()){
Toast.makeText(getApplicationContext(),"Plz Enter Username",Toast.LENGTH_SHORT).show();
}else if(!((username.length() > 6) && (username.length() < 15))){
Toast.makeText(getApplicationContext(),"Username > 6 and < 15",Toast.LENGTH_SHORT).show();
}
//PASSWORD VALIDATION
if(password.isEmpty()){
Toast.makeText(getApplicationContext(),"Plz Enter Password",Toast.LENGTH_SHORT).show();
}else if(!((password.length() > 6) && (password.length() < 15))){
Toast.makeText(getApplicationContext(),"Password > 6 and < 15",Toast.LENGTH_SHORT).show();
}
}
});
}
}
If you want to display all toasts one by one, then you need to create a new class and write your own logic. I can give you a solution.
First create a new class as below.
ToastManager.java
class ToastManager {
private final WeakReference<Context> mContext;
private final Handler uiHandler = new Handler(Looper.getMainLooper());
private final List<Item> items = new ArrayList<>();
private int durationInMillis;
private boolean isShowing;
private int delayedBetweenToastInMillis;
public ToastManager(Context context) {
mContext = new WeakReference<>(context);
}
public void addToast(String message, #NonNull Duration duration) {
Item item = new Item(message, duration);
items.add(item);
}
public void show() {
// Prevent client from calling this method many time.
if (isShowing) {
return;
}
// Show all toast on screen.
showToast();
// After calling show(), if client add new toasts by calling addToast()
// Then we must show them on screen. Otherwise reset all data of this class.
uiHandler.postDelayed(new Runnable() {
#Override
public void run() {
if (!items.isEmpty()) {
showToast();
} else {
reset();
}
}
}, durationInMillis);
}
public void setDelayedBetweenToast(int delayInMillis) {
delayedBetweenToastInMillis = delayInMillis;
}
public void cancel() {
reset();
uiHandler.removeCallbacksAndMessages(null);
}
private void showToast() {
List<Item> list = new ArrayList<>(items);
items.clear();
durationInMillis = 0;
for (Item item : list) {
uiHandler.postDelayed(new Runnable() {
#Override
public void run() {
Toast.makeText(mContext.get(), item.text, item.getDurationForToast()).show();
}
}, durationInMillis);
durationInMillis += item.getDurationInMillis() + delayedBetweenToastInMillis;
}
}
private void reset() {
items.clear();
durationInMillis = 0;
isShowing = false;
}
private static class Item {
String text;
Duration duration;
Item(String text, Duration duration) {
this.text = text;
this.duration = duration;
}
int getDurationForToast() {
return duration == Duration.LENGTH_SHORT ? Toast.LENGTH_SHORT : Toast.LENGTH_LONG;
}
int getDurationInMillis() {
return duration == Duration.LENGTH_SHORT ? 2000 : 3500;
}
}
enum Duration {
LENGTH_SHORT,
LENGTH_LONG
}
}
Then use it from your class.
NewUserActivity.java
// Create a new instance of ToastManager
ToastManager toastManager = new ToastManager(NewUserActivity.this);
// NAME VALIDATION
if (NAME.isEmpty()) {
toastManager.addToast("Plz Enter Name", ToastManager.Duration.LENGTH_SHORT);
} else if (!((NAME.length() > 3) && (NAME.length() < 15))) {
toastManager.addToast("Name > 3 and < 15", ToastManager.Duration.LENGTH_SHORT);
} else if (!NAME.matches("[a-zA-Z ]+")) {
toastManager.addToast("Only enter alphabets", ToastManager.Duration.LENGTH_SHORT);
}
//EMAIL VALIDATION
if (EMAIL.isEmpty()) {
toastManager.addToast("Plz Enter Email", ToastManager.Duration.LENGTH_SHORT);
} else if (!(EMAIL.matches(emailPattern))) {
toastManager.addToast("Invalid Email", ToastManager.Duration.LENGTH_SHORT);
}
//PHONE NUMBER VALIDATION
if (PHONENO.isEmpty()) {
toastManager.addToast("Plz Enter Phone no.", ToastManager.Duration.LENGTH_SHORT);
} else if (!(PHONENO.length() == 10)) {
toastManager.addToast("Invalid Phone no.", ToastManager.Duration.LENGTH_SHORT);
} else if (!(PHONENO.matches(phonePattern))) {
toastManager.addToast("Invalid Phone Number", ToastManager.Duration.LENGTH_SHORT);
}
//USERNAME VALIDATION
if (username.isEmpty()) {
toastManager.addToast("Plz Enter Username", ToastManager.Duration.LENGTH_SHORT);
} else if (!((username.length() > 6) && (username.length() < 15))) {
toastManager.addToast("Plz Enter Username", ToastManager.Duration.LENGTH_SHORT);
}
//PASSWORD VALIDATION
if (password.isEmpty()) {
toastManager.addToast("Plz Enter Password", ToastManager.Duration.LENGTH_SHORT);
} else if (!((password.length() > 6) && (password.length() < 15))) {
toastManager.addToast("Password > 6 and < 15", ToastManager.Duration.LENGTH_SHORT);
}
// When one or all Edit Text are blank
toastManager.addToast("All fields are compulsory", ToastManager.Duration.LENGTH_SHORT);
// Finally show all toast all screen
toastManager.show();
If you want to set extra time between toast:
toastManager.setDelayedBetweenToast(1000); // 1 second
If you don't want the toast still show when the activity is no longer visible (usually put this line onStop() method).
#Override
protected void onStop() {
toastManager.cancel();
super.onStop();
}
You can use Toast.LENGTH_LONG to make it longer.
As far as I know, there is no option to set a specific time to show the toast.
The times for the toasts are below:
int LENGTH_SHORT = 2000; // 2 seconds
int LENGTH_LONG = 3500; // 3.5 seconds
You could go around this by adding the values together.
For Example:
Toast.makeText(this, "Hello World!", Toast.LENGTH_LONG).show();
Toast.makeText(this, "Hello World!", Toast.LENGTH_LONG).show();
To get a toast of a total length of 7 seconds because 3.5s + 3.5s = 7s
I have 2 buttons for the quality. If the quality is set by typing first, the buttons work well, but if I don't write any quantity and I want to set it by plus button, the app crash.
increaseQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String textQuantity = quantity.getText().toString();
givenQuantity = Integer.parseInt(textQuantity);
quantity.setText(String.valueOf(givenQuantity + 1));
}
});
decreaseQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String textQuantity = quantity.getText().toString();
givenQuantity = Integer.parseInt(textQuantity);
//To validate if quantity is greater than 0
if ((givenQuantity - 1) >= 0) {
quantity.setText(String.valueOf(givenQuantity - 1));
} else {
Toast.makeText(EditorActivity.this, R.string.quantity_no_less_then_0, Toast.LENGTH_SHORT).show();
return;
}
}
});
Surround all your parsing lines with try/catch, like:
try {
givenQuantity = Integer.parseInt(textQuantity);
} catch (NumberFormatException e) {
e.printStackTrace();
givenQuantity = 0;
}
when the EditText is empty, a NumberFormatException is thrown because an empty string can not be parsed to int.
check is edittext is empty or not. If empty show toast message to user asking to enter some value to calculate.
I have a dynamically added EditTexts to my layout. They don't have id's. This EditTexts are all required and cannot be left empty. I have this function for validation:
private boolean validate() {
boolean valid = true;
for (int i = 0; i < layout.getChildCount(); i++) {
if (layout.getChildAt(i).getTag() != null && layout.getChildAt(i).getTag().toString().contains("required")) {
String viewClass = layout.getChildAt(i).getClass().getName();
if (viewClass.contains("EditText")) {
EditText et = (EditText) layout.getChildAt(i);
if (et.getText().toString().trim().isEmpty()) {
Log.d("#########", "EDIT TEXT ERROR");
et.setError("This field is required.", getResources().getDrawable(R.drawable.indicator_input_error));
valid = false;
}
}
}
}
}
where layout is my layout containing the EditTexts. It gives me the log but it's not showing the error. If I change the setError line with
et.setText("#########");
the text is changed properly. Why isn't the error showing?
It was some other mistake. The code in the question is working fine.
private boolean validate() {
boolean valid = false;
System.out.println("getChildCount:"+ll.getChildCount());
Log.d(TAG,"*****************1******************");
for (int i = 0; i < ll.getChildCount(); i++) {
if (ll.getChildAt(i).getTag() != null && ll.getChildAt(i).getTag().toString().contains("required")) {
Log.d(TAG,"*****************2******************");
String viewClass = ll.getChildAt(i).getClass().getName();
if (viewClass.contains("EditText")) {
Log.d(TAG,"*****************3******************");
EditText et = (EditText) ll.getChildAt(i);
if (et.getText().toString().trim().isEmpty()) {
Log.d(TAG,"*****************4******************");
Log.d("#########", "EDIT TEXT ERROR");
Utils.showAlertDialog(activity, "Error", "The fields are required",getResources().getDrawable(R.mipmap.ic_error), new DialogInterface.OnClickListener() {
#Override`enter code here`
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
valid = true;
}else{
Log.d(TAG,"**********else*******1******************");
valid = false;
}
}else{
Log.d(TAG,"********else*********2******************");
valid = false;
}
}else{
Log.d(TAG,"*********else********3******************");
valid = false;
}
}
return valid;
}
and try to call
if(validate()) {
Log.d(TAG,"********validate()*********1******************");
SaveRecords();
}else{
Log.d(TAG,"**********else*******1******************");
Utils.showAlertDialog(activity, "Error", "The fields are required",getResources().getDrawable(R.mipmap.ic_error), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
This question already has answers here:
How do I check if my EditText fields are empty? [closed]
(30 answers)
Closed 9 years ago.
My code does not print empty edit text itry trim stirng .length==00 but is not work hat wrong in my code?? how do my code check if edittext is empty before sumbit query
I want to check before submit method if edittext is empty? If is empty then print toast message
public class AgAppTransPayExternalAccount extends Activity {
TextView lblTPEAWelcomeToPayExternalAccountPage;
TextView lblTPEAOtherAccount;
TextView lblTPEAPinno;
TextView lblTPEAAmount;
EditText txtTPEAotheraccount;
EditText txtTPEApinno;
EditText txtTPEAamount;
Button btnTPEAsubmit;
Button clearTPEAButton;
Button btnTPEAgoback;
String sms;
public static ProgressDialog PayExternalAccountProgressDialog = null;
public static boolean value=true;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agapptranspayexternalaccount);
sms=LoginScreen.item.toString();
/*
lblTPEAWelcomeToPayExternalAccountPage = (TextView)
findViewById(R.id.lblTPEAWelcomeToPayExternalAccountPage);
lblTPEAWelcomeToPayExternalAccountPage.setText("Welcome To Pay External
Account Page");
lblTPEAWelcomeToPayExternalAccountPage.setTextColor(getResources().getColor
(R.color.text_color_black));
*/
lblTPEAOtherAccount = (TextView) findViewById(R.id.lblTPEAOtherAccount);
lblTPEAOtherAccount.setText("Other Account :");
txtTPEAotheraccount=(EditText) findViewById(R.id.txtTPEAotheraccount);
lblTPEAPinno = (TextView) findViewById(R.id.lblTPEAPinno);
lblTPEAPinno.setText("PIN Number :");
txtTPEApinno=(EditText) findViewById(R.id.txtTPEApinno);
lblTPEAAmount = (TextView) findViewById(R.id.lblTPEAAmount);
lblTPEAAmount.setText("Amount :");
txtTPEAamount=(EditText) findViewById(R.id.txtTPEAamount);
btnTPEAsubmit=(Button) findViewById(R.id.btnTPEAsubmit);
btnTPEAsubmit.setTextColor(getResources().getColor(R.color.text_color_blue));
clearTPEAButton=(Button) findViewById(R.id.clearTPEAButton);
clearTPEAButton.setTextColor(getResources().getColor(R.color.text_color_blue));
btnTPEAgoback=(Button) findViewById(R.id.btnTPEAgoback);
btnTPEAgoback.setTextColor(getResources().getColor(R.color.text_color_blue));
clearTPEAButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
txtTPEAotheraccount.setText("");
txtTPEApinno.setText("");
txtTPEAamount.setText("");
}
});
btnTPEAgoback.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
finish();
}
});
btnTPEAsubmit.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
String tpeapinemptycheck = txtTPEApinno.getText().toString();
String otheraccountemptycheck =
lblTPEAOtherAccount.getText().toString();
String amountemptycheck = txtTPEAamount.getText().toString();
if (tpeapinemptycheck.trim().equals("")||
(otheraccountemptycheck.trim().equals("")) ||(amountemptycheck.trim().equals("")))
{
Toast.makeText(getApplicationContext(), "Please Enter
Correct Information", Toast.LENGTH_LONG).show();
}
else
showProgress();
submitPEA();
}
});
}
private void submitPEA() {
String message;
String mobilenumber= LoginScreen.smsmobileno;
if (( sms.compareTo("SMS")==0))
{
SmsManager smsmanager = SmsManager.getDefault();
message="AGPEA"+AgAppHelperMethods.varMobileNo+AgAppHelperMethods.
arMobileNo+txtTPEAotheraccount.getText().toString()+AgAppHelperMethods.
varMobileNo+txtTPEApinno.getText().toString()+txtTPEAamount.getText().toString();
smsmanager.sendTextMessage(mobilenumber, null, message, null, null);
}
else
{
Intent j = new Intent(AgAppTransPayExternalAccount.this, AgAppTransPEAResponse.class);
Bundle bundle = new Bundle();
bundle.putString("txtTPEApinno", txtTPEApinno.getText().toString());
bundle.putString("txtTPEAotheraccount",txtTPEAotheraccount.getText().toString());
bundle.putString("txtTPEAamount",txtTPEAamount.getText().toString());
j.putExtras(bundle);
startActivity(j);
value=false;
PayExternalAccountProgressDialog.dismiss();
}
}
private void showProgress()
{
PayExternalAccountProgressDialog =
ProgressDialog.show(AgAppTransPayExternalAccount.this,null, "Processing please
wait...", true);
if (PayExternalAccountProgressDialog != null) {
try
{
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
PayExternalAccountProgressDialog.dismiss();
if(value)
{
Toast.makeText(AgAppTransPayExternalAccount.this, "Request
TimeOut " , Toast.LENGTH_SHORT).show();
}
}
}, 15000); // <--- here is the time adjustment.
}
catch (Exception e)
{
}
}
}
}
Your code is right, only missing this is { } braces in the else condition, try out as following,
if (tpeapinemptycheck.trim().equals("")||
(otheraccountemptycheck.trim().equals("")) ||(amountemptycheck.trim().equals("")))
{
Toast.makeText(getApplicationContext(), "Please Enter
Correct Information", Toast.LENGTH_LONG).show();
}
else
{ // add this
showProgress();
submitPEA();
} // add this
Just because you haven't added those { } braces, your control was going into submitPEA() method.
Try like this
edit_text.getText().toString().trim().equals("");
Create a String variable say x;
Now if et is your EditText field use this:
x = et.getText().toString();
if the EditText field has any text in it it would be passed to the string x.
Now to check if the string x is not null or contains nothing use
if(x.matches(""))
{
//your code here
}
else
{
//the counter action you'll take
}
this way you can check that the entry you are about to enter in the database won't be empty.
Happy coding.
btnNadoplata.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
long inputValue1 = Long.parseLong(text1.getText().toString());
String encodedHash = Uri.encode("#");
if (text1.getText().length() == 14 ) {
startActivity(new Intent("android.intent.action.CALL", Uri.parse("tel:*123*" + inputValue1 + encodedHash)));
}else {
Toast.makeText(bonbon.this, "Krivi kod. Unesi 14-znamenkasti kod sa bona!", Toast.LENGTH_SHORT).show();
}
}
});
I have one editText, in wich user needs to input a number14 digit number. If number is less or more than an 14 digits, when user clikc on button, he gets the message that say input is not good. The problem is when editText is empty, and user click on button, app crashes. how can i change this, so if editText is empty, user gets message from above code part ??
Sory for my bad english.
It might crash on this line:
long inputValue1 = Long.parseLong(text1.getText().toString());
In fact, if you have an empty string in your EditText text1, the function parseLong() will throw a NumberFormatException exception.
You should test the value of the text of text1 before continuing:
public void onClick(View v)
{
if (text1.getText().toString().compareTo("") == 0)
{
long inputValue1 = Long.parseLong(text1.getText().toString());
String encodedHash = Uri.encode("#");
...
Or you can add try/catch instruction to catch the exception thrown by Long.parseLong().
public void onClick(View v)
{
try
{
long inputValue1 = Long.parseLong(text1.getText().toString());
String encodedHash = Uri.encode("#");
...
}
catch (NumberFormatException nfe)
{
...
}
You should test your input length before parsing. Parsing crashes.
public void onClick(View v)
{
if( text1.getText().length() <14 )
{
Toast.makeText(bonbon.this, "Krivi kod. Unesi 14-znamenkasti kod sa bona!", Toast.LENGTH_SHORT).show();
return;
}//if
long inputValue1 = Long.parseLong(text1.getText().toString());
String encodedHash = Uri.encode("#");
startActivity(new Intent("android.intent.action.CALL", Uri.parse("tel:*123*" + inputValue1 + encodedHash)));
}//met
An alternative could be to surround parsing with a try/catch/block, but it's less efficient than this simple test, but more robust if user types non digits.
Regards,
Stéphane
objText = (EditText)findViewById(R.id.txtPurchasePrice);
String strPurchasePrice = objText.getText().toString();
objText = (EditText)findViewById(R.id.txtSalePrice);
String strSalePrice = objText.getText().toString();
objText = (EditText)findViewById(R.id.txtShares);
String strShares = objText.getText().toString();
if(strPurchasePrice.trim().equals("") && strSalePrice.trim().equals("") && strShares.trim().equals("")) {
Toast.makeText(getApplicationContext(), "Please insert the Values..", 10000).show();
}