how to increase time of toast msg [duplicate] - android

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

Related

Check if user input is equal to string array

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();
}

Android If statement not breaking when condition is true

In this activity I am creating an account for users. I am using mobsandgeeks.saripaar API for validation features. To allow the activity to work I currently print the errors to an invisible text field, if this textfield has text, the activity does not go onto the next activity (i.e. there is an issue with user input).
I am having a problem with the if statement that checks if the username or email already exists in the database. When condition is true (checked in logs), the account is not created, but the 'Account created' message is still displayed and the application still goes to the next activity.
Any help on this would be much appreciated. Thanks
CreateAccount.java
DatabaseHelper myDb;
private static final String TAG = "CreateAccount";
//http://learningprogramming.net/mobile/android/form-validation-in-android/
#NotEmpty
#Length(min = 3, max = 10)
private EditText etUsername;
#NotEmpty
private EditText etUserAddress;
#NotEmpty
private EditText etFirstName;
#NotEmpty
private EditText etLastName;
#NotEmpty
#Email
private EditText etEmail;
#NotEmpty
#Pattern(regex = "(^\\(?([0-9]{3})\\)?[-.\\s]?([0-9]{3})[-.\\s]?([0-9]{4})$)")
private EditText etPhone;
#NotEmpty
private EditText etPaypal;
//Valid = abcABC123!
#NotEmpty
#Password(scheme = Password.Scheme.ALPHA_NUMERIC_SYMBOLS)
private EditText etPassword;
#ConfirmPassword
EditText etConfirmPassword;
Button btnCreateAccount;
TextView check;
//https://www.youtube.com/watch?v=rt-8PgncIio
ImageView profileImageView;
Button btnProfilePic;
private static final int SELECT_PHOTO = 1;
private static final int CAPTURE_PHOTO = 2;
ProgressDialog progressBar;
int progressBarStatus;
Handler progressBarHandler = new Handler();
Bitmap thumbnail;
private Validator validator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_account);
myDb = new DatabaseHelper(this);
validator = new Validator(this);
validator.setValidationListener(this);
etUsername = findViewById(R.id.etUsername);
etFirstName = findViewById(R.id.etFirstName);
etLastName = findViewById(R.id.etLastName);
etUserAddress = findViewById(R.id.etAddress);
etEmail = findViewById(R.id.etEmail);
etPassword = findViewById(R.id.etPasswordLogin);
etConfirmPassword = findViewById(R.id.etConfirmPasswordLogin);
etPhone = findViewById(R.id.etPhoneNo);
etPaypal = findViewById(R.id.etPaypalName);
btnCreateAccount = findViewById(R.id.btnCreateAccount);
check = findViewById(R.id.tvCheck);
btnProfilePic = findViewById(R.id.btnProfilePicture);
profileImageView = findViewById(R.id.imageProfile);
btnProfilePic.setOnClickListener(this);
//(https://www.youtube.com/watch?v=rt-8PgncIio) Image
//had to change permissions in the Android Manifest file to allow for camera to be used
if (ContextCompat.checkSelfPermission(CreateAccount.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
profileImageView.setEnabled(false);
ActivityCompat.requestPermissions(CreateAccount.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
} else {
profileImageView.setEnabled(true);
}
createAccount();
}
public void createAccount() {
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validator.validate();
//(https://www.youtube.com/watch?v=rt-8PgncIio) Image
profileImageView.setDrawingCacheEnabled(true);
profileImageView.buildDrawingCache();
Bitmap bitmap = profileImageView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
String email1 = etEmail.getText().toString().trim();
Log.d(TAG, "onClick: email " + email1);
String username = etUsername.getText().toString().trim();
Log.d(TAG, "onClick: username " + username);
boolean emailExists = myDb.checkIfEmailAlreadyExists(email1);
Log.d(TAG, "onClick: emailExists " + emailExists);
boolean usernameExists = myDb.checkIfUsernameAlreadyExists(username);
Log.d(TAG, "onClick: usernameExists " + usernameExists);
//https://stackoverflow.com/questions/6290531/check-if-edittext-is-empty
if (etUsername.getText().toString().matches("") | etFirstName.getText().toString().matches("") | etLastName.getText().toString().matches("")
| etEmail.getText().toString().matches("") | etUserAddress.getText().toString().matches("") | etPassword.getText().toString().matches("")|
etConfirmPassword.getText().toString().matches("") | etPhone.getText().toString().matches("") | etPaypal.getText().toString().matches(""))
{
Toast.makeText(CreateAccount.this, "Please fill empty fields", Toast.LENGTH_LONG).show();
}
else if(check.getText().toString().matches("") == false) {
Toast.makeText(CreateAccount.this, "Please enter correct details", Toast.LENGTH_SHORT).show();
}
else {
if (usernameExists){
Log.d(TAG, "onClick: userExists " + usernameExists);
Toast.makeText(CreateAccount.this, "This username is already registered", Toast.LENGTH_LONG).show();
check.setText("TEXT");
}
else if (emailExists){
Log.d(TAG, "onClick: emailExists" + emailExists);
Toast.makeText(CreateAccount.this, "This email is already registered", Toast.LENGTH_LONG).show();
check.setText("TEXT");
}
else if (usernameExists == false | emailExists == false) {
boolean checktext = check.getText().equals("");
// original CRUD video - https://www.youtube.com/watch?v=kDZES1wtKUY&list=PLS1QulWo1RIaRdy16cOzBO5Jr6kEagA07&index=8
boolean isInserted = myDb.insertUserData(etUsername.getText().toString(), etUserAddress.getText().toString(), etFirstName.getText().toString(), etLastName.getText().toString(),
etEmail.getText().toString(), etPassword.getText().toString(), etPhone.getText().toString(),
etPaypal.getText().toString(), data);
if (isInserted == true) {
if (checktext == true) {
onValidationSucceeded();
}
else if (checktext == false){
Toast.makeText(CreateAccount.this, "Account not Created", Toast.LENGTH_LONG).show();
}
}
} else {
Toast.makeText(CreateAccount.this, "Account not Created", Toast.LENGTH_LONG).show();
}
}
}
});
}
//http://learningprogramming.net/mobile/android/form-validation-in-android/
#Override
public void onValidationFailed(List<ValidationError> errors) {
for (ValidationError error : errors) {
View view = error.getView();
//TextView check = findViewById(R.id.tvCheck);
String message = error.getCollatedErrorMessage(this);
// Display error messages
if (view instanceof EditText) {
((EditText) view).setError(message);
} else {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
check.setText(errors.toString());
}
}
//http://learningprogramming.net/mobile/android/form-validation-in-android/
#Override
public void onValidationSucceeded() {
Toast.makeText(CreateAccount.this, "Account Created, Please sign in", Toast.LENGTH_LONG).show();
Intent intent = new Intent(CreateAccount.this, Login.class);
startActivity(intent);
}
You have a problem in your condition:
Instead of:
else if (usernameExists == false | emailExists == false)
It should be:
else if (usernameExists == false && emailExists == false)
which means user/email not exist, insert them in DB and navigate to next activity.

Email id and phone number not validating

Hi In My application checking validation for email id and phone number but it's not validating both and simply it's saving into database.
I want to check the email id and phone number if it's both correct i want to do next process
Can any one please help me
ContactUs.java
public class ContactUs extends Activity
{
EditText fname1,lname1,mobile1,altmob1,email1,comment1;
String data="";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.contactus);
fname1=(EditText) findViewById(R.id.fname);
lname1=(EditText) findViewById(R.id.lname);
mobile1=(EditText) findViewById(R.id.mobile);
altmob1=(EditText) findViewById(R.id.altno);
email1=(EditText) findViewById(R.id.email);
comment1=(EditText) findViewById(R.id.coment);
Button Send = (Button) findViewById(R.id.Send);
Send.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
String fname = fname1.getText().toString();
String lname = lname1.getText().toString();
String mobile = mobile1.getText().toString();
String altmob = altmob1.getText().toString();
String email = email1.getText().toString();
String comment = comment1.getText().toString();
if(fname.equals(""))
{
fname1.setError( "Please Enter First Name" );
}
else if(lname.equals(""))
{
lname1.setError( "Please Enter Last Name" );
}
else if(mobile.equals(""))
{
mobile1.setError( "Please Enter Mobile No." );
isValidMobile(mobile);
}
else if(altmob.equals(""))
{
altmob1.setError( "Please Enter Altenative Mobile No." );
}
else if(email.equals(""))
{
email1.setError( "Please Enter EmailId" );
isValidMail(email);
}
else if(comment.equals(""))
{
comment1.setError( "Please Enter Your Comments here" );
}
else
{
try{
String queryString ="fname="+ fname
+"&lname="+lname+"&mobile="+mobile+ "&altmob="+altmob+"&email="+email+"&comment="+comment;
data = DatabaseUtility.executeQueryPhp("Contactform",queryString);
fname1.setText("");
lname1.setText("");
mobile1.setText("");
altmob1.setText("");
email1.setText("");
comment1.setText("");
Toast.makeText(
ContactUs.this,
"Message:Records Saved Sucessfully",
Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
private boolean isValidMail(String email)
{
boolean check;
Pattern p;
Matcher m;
String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
p = Pattern.compile(EMAIL_STRING);
m = p.matcher(email);
check = m.matches();
if(!check)
{
email1.setError("Not Valid Email");
}
return check;
}
private boolean isValidMobile(String mobile)
{
boolean check;
if(mobile.length() < 6 || mobile.length() > 13)
{
check = false;
mobile1.setError("Not Valid Number");
}
else
{
check = true;
}
return check;
}
there are edittext box with property email
android:inputType="textEmailAddress"
in your code
else if(mobile.equals(""))
{
mobile1.setError( "Please Enter Mobile No." );
isValidMobile(mobile);
}
it check if email in blank then go to isValidMobile
so use
else if(mobile.equals(""))
{
mobile1.setError( "Please Enter Mobile No." );
}
else if(!isValidMobile(mobile)){
// do somting
}
and similar for email
You are running your valid email check but ignoring the result. As long as you enter some text the call to save will work.
If you incorporate the return values from your is valid check methods, you can stop saving when those calls return false.
e.g.
if(mobile.equals(""))
{
mobile1.setError( "Please Enter Mobile No." );
}
else if(!isValidMobile(mobile))
{
mobile1.setError("Not Valid Number");
}
Try this for checking email:
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
For telephone number check:
public final static boolean isValidPhone(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.PHONE.matcher(target).matches();
}
}
And please update your code with as :
public class ContactUs extends Activity {
EditText fname1, lname1, mobile1, altmob1, email1, comment1;
String data = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactus);
fname1 = (EditText) findViewById(R.id.fname);
lname1 = (EditText) findViewById(R.id.lname);
mobile1 = (EditText) findViewById(R.id.mobile);
altmob1 = (EditText) findViewById(R.id.altno);
email1 = (EditText) findViewById(R.id.email);
comment1 = (EditText) findViewById(R.id.coment);
Button Send = (Button) findViewById(R.id.Send);
Send.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String fname = fname1.getText().toString().trim();
String lname = lname1.getText().toString().trim();
String mobile = mobile1.getText().toString().trim();
String altmob = altmob1.getText().toString().trim();
String email = email1.getText().toString().trim();
String comment = comment1.getText().toString().trim();
if (fname.length() != 0) {
if (lname.length() != 0) {
if (mobile.length() != 0 && isValidMobile(mobile)) {
if (altmob.length() != 0 && isValidMobile(altmob)) {
if (email.length() != 0 && isValidMail(email)) {
if (comment.length() != 0) {
try {
String queryString = "fname="
+ fname + "&lname=" + lname
+ "&mobile=" + mobile
+ "&altmob=" + altmob
+ "&email=" + email
+ "&comment=" + comment;
data = DatabaseUtility
.executeQueryPhp(
"Contactform",
queryString);
fname1.setText("");
lname1.setText("");
mobile1.setText("");
altmob1.setText("");
email1.setText("");
comment1.setText("");
Toast.makeText(
ContactUs.this,
"Message:Records Saved Sucessfully",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
} else {
comment1.setError("Please Enter Your Comments here");
}
} else {
email1.setError("Please Enter Valid EmailId");
}
} else {
altmob1.setError("Please Enter Altenative Mobile No.");
}
} else {
mobile1.setError("Please Enter valid Mobile No.");
}
} else {
lname1.setError("Please Enter Last Name");
}
} else {
fname1.setError("Please Enter First Name");
}
}
});
}
private boolean isValidMail(String email) {
boolean check;
Pattern p;
Matcher m;
String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
p = Pattern.compile(EMAIL_STRING);
m = p.matcher(email);
check = m.matches();
if (!check) {
email1.setError("Not Valid Email");
}
return check;
}
private boolean isValidMobile(String mobile) {
boolean check;
if (mobile.length() < 6 || mobile.length() > 13) {
check = false;
mobile1.setError("Not Valid Number");
} else {
check = true;
}
return check;
}
}

Android Email Validation on EditText

I have one edittext and I would to to write email validation in my Editttext
this is a xml code
<EditText
android:id="#+id/mail"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_alignLeft="#+id/phone"
android:layout_below="#+id/phone"
android:layout_marginRight="33dp"
android:layout_marginTop="10dp"
android:background="#drawable/edit_background"
android:ems="10"
android:hint="E-Mail"
android:inputType="textEmailAddress"
android:paddingLeft="20dp"
android:textColor="#7e7e7e"
android:textColorHint="#7e7e7e" >
</EditText>
and this is a java code
emailInput = mail.getText().toString().trim();
emailPattern = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
if (emailInput.matches(emailPattern)) {
Toast.makeText(getActivity(), "valid email address", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Invalid email address", Toast.LENGTH_SHORT).show();
mail.setBackgroundResource(R.drawable.edit_red_line);
}
I can't validation. The toast message is always "Invalid email address".
What am I doing wrong?
Why not use:
public final static boolean isValidEmail(CharSequence target) {
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
As suggested here.
I am posting very simple and easy answer of email validation without using any string pattern.
1.Set on click listener on button....
button_resetPassword.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
CharSequence temp_emilID=username.getText().toString();//here username is the your edittext object...
if(!isValidEmail(temp_emilID))
{
username.requestFocus();
username.setError("Enter Correct Mail_ID ..!!");
or
Toast.makeText(getApplicationContext(), "Enter Correct Mail_ID", Toast.LENGTH_SHORT).show();
}
else
{
correctMail..
//Your action...
}
});
2.call the isValidEmail() i.e..
public final static boolean isValidEmail(CharSequence target)
{
if (TextUtils.isEmpty(target))
{
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
I hope it will helpful for you...
Android Email Validation Simplest way
String validemail= "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\#" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+";
String emal=email.getText().toString();
Matcher matcherObj = Pattern.compile(validemail).matcher(emal);
if (matcherObj.matches()) {
Toast.makeText(getApplicationContext(), "enter
all details", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),"please enter
valid email",Toast.LENGTH_SHORT).show();
}
Try following code:
public final static boolean isValidEmail(CharSequence target) {
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
This works fine.
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if(emailId.getText().toString().isEmpty()) {
Toast.makeText(getApplicationContext(),"enter email address",Toast.LENGTH_SHORT).show();
else {
if (emailId.getText().toString().trim().matches(emailPattern)) {
Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),"Invalid email address", Toast.LENGTH_SHORT).show();
}
}
here is a whole code for login validations......
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "LoginActivity";
private static final int REQUEST_SIGNUP = 0;
#Bind(R.id.input_email) EditText _emailText;
#Bind(R.id.input_password) EditText _passwordText;
#Bind(R.id.btn_login) Button _loginButton;
#Bind(R.id.link_signup) TextView _signupLink;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
_loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
_signupLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Start the Signup activity
Intent intent = new Intent(getApplicationContext(), SignupActivity.class);
startActivityForResult(intent, REQUEST_SIGNUP);
finish();
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
});
}
public void login() {
Log.d(TAG, "Login");
if (!validate()) {
onLoginFailed();
return;
}
_loginButton.setEnabled(false);
final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this,
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Authenticating...");
progressDialog.show();
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
// TODO: Implement your own authentication logic here.
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
// On complete call either onLoginSuccess or onLoginFailed
onLoginSuccess();
// onLoginFailed();
progressDialog.dismiss();
}
}, 3000);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SIGNUP) {
if (resultCode == RESULT_OK) {
// TODO: Implement successful signup logic here
// By default we just finish the Activity and log them in automatically
this.finish();
}
}
}
#Override
public void onBackPressed() {
// Disable going back to the MainActivity
moveTaskToBack(true);
}
public void onLoginSuccess() {
_loginButton.setEnabled(true);
finish();
}
public void onLoginFailed() {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
_loginButton.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
_passwordText.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
return valid;
}
}
Use this function for validating email id:
private boolean validateEmaillId(String emailId){
return Pattern.compile("^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))#"
+ "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
+ "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$").matcher(emailId).matches();
}
I had a query in email pattern for more than one Email ID validation and for only one Email ID.I solved it by using :
public static final String patter_emails="^(\\s*,?\\s*[0-9a-za-z]([-.\\w]*[0-9a-za-z])*#([0-9a-za-z][-\\w]*[0-9a-za-z]\\.)+[a-za-z]{2,9})+\\s*$";
public static final String patter_email="^(\\s*[0-9a-za-z]([-.\\w]*[0-9a-za-z])*#([0-9a-za-z][-\\w]*[0-9a-za-z]\\.)+[a-za-z]{2,9})+\\s*$";
These above is used for pattern in Java and Android both.
check this by using:
pattern test: rubular.com
android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches()
private void isValidEmail(String email_id) {
if (email_id == null){
checkTextView.setVisibility(View.VISIBLE);
checkTextView.setText(LocaleController.getString("EnterValidEmail", R.string.EnterValidEmail));
return;
}
if (android.util.Patterns.EMAIL_ADDRESS.matcher(email_id).matches()) {
checkTextView.setVisibility(View.GONE);
} else {
checkTextView.setVisibility(View.VISIBLE);
checkTextView.setText(LocaleController.getString("EnterValidEmail", R.string.EnterValidEmail));
}
Take a textView ex.checkTextView and validate when the email is valid then the textview is gone otherwise it show the message
Try this code
String emailPattern = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
if (!tvEmail.matches(Constants.emailPattern)){
tvEmail.setError("Invalid Email ");
}
else{
//your code
}
String emailPattern = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
if (!"anan.pp#gmail.co".matches(Constants.emailPattern)){
//tvEmail.setError("Invalid Email ");
} else {
// your code
}
Try below code:
Just call below method like,
if(emailValidator(mail.getText().toString())){
Toast.makeText(getActivity(), "valid email address",
Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "invalid email address",
Toast.LENGTH_SHORT).show();
}
public static boolean emailValidator(final String mailAddress) {
Pattern pattern;
Matcher matcher;
final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(mailAddress);
return matcher.matches();
}
Assign a String variable to store the value of this EditText:
emailInput = mail.getText().toString().trim();
Use setError in your EditText:
if(!isValidEmail(emailInput)){
mail.setError("Invalid"); /*"Invalid Text" or something like getString(R.string.Invalid)*/
mail.requestFocus();
}
Create a method to check the email:
private boolean isValidEmail(String emailInput) {
String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(emailInput);
return matcher.matches();
}

How to check empty edittext in android [duplicate]

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.

Categories

Resources