What I aim with my program is to make a profile page with details that are blank for the first time use then these details can be editable and retained after clicking an update button. However, I tried many different ways like sharedprefs and firebase. It's just doesn't work to me.
The firebase way is after the update button has been clicked, it's just going to the main activity then it doesn't update or change anything.
here is the firebase code
showAllUserData();
//DB
reference = FirebaseDatabase.getInstance("https://backend-d820a-default-rtdb.firebaseio.com/").getReference("user");
private void showAllUserData(){
Intent intent = getIntent();
_NAME = intent.getStringExtra("name");
_NUMBER = intent.getStringExtra("num");
_ADDRESS = intent.getStringExtra("add");
_AGE = intent.getStringExtra("age");
_BDAY = intent.getStringExtra("bday");
_BTYPE = intent.getStringExtra("btype");
_COMORB = intent.getStringExtra("comorb");
editName.setText(_NAME);
editNum.setText(_NUMBER);
editAdd.setText(_ADDRESS);
editAge.setText(_AGE);
editBday.setText(_BDAY);
editBType.setText(_BTYPE);
editComorb.setText(_COMORB);
}
public void update(View view){
if (isNameChanged() || isNumberChanged() || isAddChanged() || isAgeChanged() ||
isBdayChanged() || isBTypeChanged() || isComorbChanged()) {
Toast.makeText(this, "Data has been updated", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "Data his same and cannot be updated", Toast.LENGTH_LONG).show();
}
}
private boolean isComorbChanged() {
if(_COMORB.equals(editComorb.getText().toString())){
reference.child(_COMORB).child("COMORB").setValue(editComorb.getText().toString());
return true;
}else{
return false;
}
}
private boolean isBTypeChanged() {
if(_BTYPE.equals(editBType.getText().toString())){
reference.child(_BTYPE).child("btype").setValue(editBType.getText().toString());
return true;
}else{
return false;
}
}
private boolean isBdayChanged() {
if(_BDAY.equals(editBday.getText().toString())){
reference.child(_BDAY).child("bday").setValue(editBday.getText().toString());
return true;
}else{
return false;
}
}
private boolean isAgeChanged() {
if(_AGE.equals(editAge.getText().toString())){
reference.child(_AGE).child("age").setValue(editAge.getText().toString());
return true;
}else{
return false;
}
}
private boolean isAddChanged() {
if(_NUMBER.equals(editNum.getText().toString())){
reference.child(_NUMBER).child("address").setValue(editNum.getText().toString());
return true;
}else{
return false;
}
}
private boolean isNumberChanged() {
if(_NUMBER.equals(editNum.getText().toString())){
reference.child(_NUMBER).child("numBER").setValue(editNum.getText().toString());
return true;
}else{
return false;
}
}
private boolean isNameChanged() {
if(_NAME.equals(editName.getText().toString())){
reference.child(_NAME).child("name").setValue(editName.getText().toString());
return true;
}else{
return false;
}
Is there a simpler way to implement this?
Related
When I run the codes, it does not show any error. I have no problem to login as guardian but when I try to login as elderly it couldn't and I don't know what's the problem. What I want is when a user input the username and password, it will validate from database and direct the user according to different user type.
Segment codes of Login.java:
private Boolean validateUsername() {
String val = username.getEditText().getText().toString();
if (val.isEmpty()) {
username.setError("Field cannot be empty");
return false;
} else {
username.setError(null);
username.setErrorEnabled(false);
return true;
}
}
private Boolean validatePassword() {
String val = password.getEditText().getText().toString();
if (val.isEmpty()) {
password.setError("Field cannot be empty");
return false;
} else {
password.setError(null);
password.setErrorEnabled(false);
return true;
}
}
public void loginUser(View view) {
//validate login info
if (!validateUsername() || !validatePassword()) {
return;
} else {
isUser();
}
}
private void isUser() {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("user").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String input1 = username.getEditText().getText().toString();
String input2 = password.getEditText().getText().toString();
if (dataSnapshot.child(input1).exists()) {
if (dataSnapshot.child(input1).child("password").getValue(String.class).equals(input2)) {
if (active.isChecked()) {
if (dataSnapshot.child(input1).child("radioGuardian").getValue(String.class).equals("Guardian")) {
preferences.setDataLogin(Login.this, true);
preferences.setDataAs(Login.this, "Guardian");
startActivity(new Intent(Login.this, dashboardGuardian.class));
} else if (dataSnapshot.child(input1).child("radioElderly").getValue(String.class).equals("Elderly")) {
preferences.setDataLogin(Login.this, true);
preferences.setDataAs(Login.this, "Elderly");
startActivity(new Intent(Login.this, dashboardUser.class));
}
} else {
if (dataSnapshot.child(input1).child("radioGuardian").getValue(String.class).equals("Guardian")) {
preferences.setDataLogin(Login.this, false);
startActivity(new Intent(Login.this, dashboardGuardian.class));
} else if (dataSnapshot.child(input1).child("radioElderly").getValue(String.class).equals("Elderly")) {
preferences.setDataLogin(Login.this, false);
startActivity(new Intent(Login.this, dashboardUser.class));
}
}
} else {
password.setError("Wrong Password");
password.requestFocus();
}
} else {
username.setError("No such User exist");
username.requestFocus();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
protected void onStart() {
super.onStart();
if (preferences.getDataLogin(this)) {
if (preferences.getDataAs(this).equals("Guardian")) {
startActivity(new Intent(this, dashboardGuardian.class));
finish();
} else {
startActivity(new Intent(this, dashboardUser.class));
finish();
}
}
}
}
Codes of Register.java:
public class Register extends AppCompatActivity {
//Variables
TextInputLayout regUsername, regEmail, regPhoneNo, regPassword;
RadioGroup radioGroup;
RadioButton selectedElderly, selectedGuardian;
Button regBtn, regToLoginBtn;
UserHelperClass helperClass;
int i = 0;
FirebaseDatabase rootNode;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//Hooks to all xml elements in activity_register.xml
regUsername = findViewById(R.id.reg_username);
regEmail = findViewById(R.id.reg_email);
regPhoneNo = findViewById(R.id.reg_phoneNo);
regPassword = findViewById(R.id.reg_password);
regBtn = findViewById(R.id.reg_btn);
regToLoginBtn = findViewById(R.id.reg_login_btn);
radioGroup = findViewById(R.id.radio_type);
selectedGuardian = findViewById(R.id.radioGuardian);
selectedElderly = findViewById(R.id.radioElderly);
helperClass = new UserHelperClass();
regBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validateUsername() && validateEmail() && validatePhoneNo() && validateUserType() && validatePassword() == true) {
Intent intent = new Intent(Register.this, Login.class);
startActivity(intent);
} else {
validateUsername();
validateEmail();
validatePhoneNo();
validateUserType();
validatePassword();
}
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("user");
//Get all the values
String m1 = selectedElderly.getText().toString();
String m2 = selectedGuardian.getText().toString();
String username = regUsername.getEditText().getText().toString();
String password = regPassword.getEditText().getText().toString();
helperClass.setUsername(regUsername.getEditText().getText().toString());
helperClass.setEmail(regEmail.getEditText().getText().toString());
helperClass.setPhoneNo(regPhoneNo.getEditText().getText().toString());
helperClass.setPassword(regPassword.getEditText().getText().toString());
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
} else {
helperClass.setRadioGuardian(m2);
}
reference.child(username).setValue(helperClass);
}
});
regToLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Register.this, Login.class);
startActivity(intent);
}
});
}
private Boolean validateUsername() {
String val = regUsername.getEditText().getText().toString();
String noWhiteSpace = "\\A\\w{4,20}\\z";
if (val.isEmpty()) {
regUsername.setError("Field cannot be empty");
return false;
} else if (val.length() >= 15) {
regUsername.setError("Username too long");
return false;
} else if (!val.matches(noWhiteSpace)) {
regUsername.setError("White space is not allowed");
return false;
} else {
regUsername.setError(null);
regUsername.setErrorEnabled(false);
return true;
}
}
private Boolean validateEmail() {
String val = regEmail.getEditText().getText().toString();
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (val.isEmpty()) {
regEmail.setError("Field cannot be empty");
return false;
} else if (!val.matches(emailPattern)) {
regEmail.setError("Invalid email address");
return false;
} else {
regEmail.setError(null);
return true;
}
}
private Boolean validatePhoneNo() {
String val = regPhoneNo.getEditText().getText().toString();
if (val.isEmpty()) {
regPhoneNo.setError("Field cannot be empty");
return false;
} else {
regPhoneNo.setError(null);
return true;
}
}
private Boolean validateUserType() {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(this, "Please select user type", Toast.LENGTH_SHORT).show();
return false;
} else {
return true;
}
}
private Boolean validatePassword() {
String val = regPassword.getEditText().getText().toString();
String passwordVal = "^" +
"(?=.*[0-9])" + //at least 1 digit
"(?=.*[a-z])" + //at least 1 lower case letter
"(?=.*[A-Z])" + //at least 1 upper case letter
"(?=.*[a-zA-Z])" + //any letter
"(?=.*[##$%^&+=])" + //at least 1 special character
"(?=\\S+$)" + //no white space
".{4,}" + //at least 4 characters
"$";
if (val.isEmpty()) {
regPassword.setError("Field cannot be empty");
return false;
} else if (!val.matches(passwordVal)) {
regPassword.setError("Password is too weak");
return false;
} else {
regPassword.setError(null);
regPassword.setErrorEnabled(false);
return true;
}
}
public void registerUser(View view) {
if (!validateUsername() | !validatePassword() | !validatePhoneNo() | !validateEmail() | validateUserType()) {
return;
}
//Get all the values
String m1 = selectedElderly.getText().toString();
String m2 = selectedGuardian.getText().toString();
helperClass.setUsername(regUsername.getEditText().getText().toString());
helperClass.setEmail(regEmail.getEditText().getText().toString());
helperClass.setPhoneNo(regPhoneNo.getEditText().getText().toString());
helperClass.setPassword(regPassword.getEditText().getText().toString());
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
} else {
helperClass.setRadioGuardian(m2);
}
reference.child(String.valueOf(i + 1)).setValue(helperClass);
}
}
Database structure
If you post your database structure that would be more helpful.
As per your code.
you have two children in input1
'radioGuardian' and 'radioElderly'
have you added both values on registration? Or it will be null. And it will produce nullPointEx.
Hence the issue is here!
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
} else {
helperClass.setRadioGuardian(m2);
}
Try to change it to:-
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
helperClass.setRadioGuardian("NA");
} else {
helperClass.setRadioGuardian(m2);
helperClass.setRadioElderly("NA");
}
I have made a fragment in which I am validating a Register form, it works fine sometime but after few seconds the app stops without showing any message nor I have any error log...I don't know what happens.
Here is my code:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_register, container, false);
RegUsername = (EditText) view.findViewById(R.id.RegUsername);
RegEmailId = (EditText) view.findViewById(R.id.RegEmailId);
RegPhoneNo = (EditText) view.findViewById(R.id.RegPhoneNo);
RegPassword = (EditText) view.findViewById(R.id.RegPassword);
RegisterButton = (Button) view.findViewById(R.id.Register);
RegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Register(); }})};
return view; }
private void Register() {
initialize();
if (!registerfail()) {
Toast.makeText(getActivity(), "Registration failed! || Try Again", Toast.LENGTH_SHORT).show();
} else {
registerok();
}
}
private void registerok() {
Toast.makeText(getActivity(), "Welcome " + Username, Toast.LENGTH_SHORT);
}
private boolean registerfail() {
boolean validation = true;
if (Username.isEmpty() || Username.length() > 25) {
RegUsername.setError("Invalid username");
validation = false;
}
if (EmailId.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(EmailId).matches()) {
RegEmailId.setError("Invalid EmailId");
validation = false; }
}
if (PhoneNo.isEmpty()) {
RegPhoneNo.setError("Invalid PhoneNo.");
validation = false; }
}
if (Password.isEmpty()) {
RegPassword.setError("Invalid Password");
validation = false;}
}
return validation; }
private void initialize() {
Username = RegUsername.getText().toString().trim();
EmailId = RegEmailId.getText().toString().trim();
PhoneNo = RegPhoneNo.getText().toString().trim();
Password = RegPassword.getText().toString().trim(); }}
//set validation = false if any if condition is failed
private boolean registerfail() {
boolean validation = true;
if (Username.isEmpty() || Username.length() > 25) {
RegUsername.setError("Invalid username");
validation = false;
}
if (EmailId.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(EmailId).matches()) {
RegEmailId.setError("Invalid EmailId");
validation = false;
}
if (PhoneNo.isEmpty()) {
RegPhoneNo.setError("Invalid PhoneNo.");
validation = false;
}
if (Password.isEmpty()) {
RegPassword.setError("Invalid Password");
validation = false;
}
return validation;
}
try this way my friend
String emailAddress = RegEmailId.getText().toString().trim();
if (RegPassword.getText().toString().length() < 6) {
RegPassword.setError(getString("password minimum contain 6 character"));
RegPassword.requestFocus();
}
if (RegPassword.getText().toString().equals("")) {
RegPassword.setError(getString("please enter password"));
RegPassword.requestFocus();
}
if (RegPhoneNo.getText().toString().equals("")) {
RegPhoneNo.setError(getString("please enter password"));
RegPhoneNo.requestFocus();
}
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(emailAddress).matches()) {
RegEmailId.setError(getString("please enter valid email address"));
RegEmailId.requestFocus();
}
if (RegEmailId.getText().toString().equals("")) {
RegEmailId.setError(getString("please enter email address"));
RegEmailId.requestFocus();
}
if (!emailAddress.equals("") &&
RegPassword.getText().toString().length() >= 6 &&
!RegPassword.getText().toString().trim().equals("")
&& android.util.Patterns.EMAIL_ADDRESS.matcher(emailAddress).matches() &&
!RegPhoneNo.getText().toString().equals("")&&
RegPhoneNo.getText().toString().length()>=10) {
// do your action
}
I have a registration form in my application which I am trying to validate. I'm facing some problems with my validation while validating the phone number and email fields.
Here is my code:
private boolean validate() {
String MobilePattern = "[0-9]{10}";
//String email1 = email.getText().toString().trim();
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (name.length() > 25) {
Toast.makeText(getApplicationContext(), "pls enter less the 25 character in user name", Toast.LENGTH_SHORT).show();
return true;
} else if (name.length() == 0 || number.length() == 0 || email.length() ==
0 || subject.length() == 0 || message.length() == 0) {
Toast.makeText(getApplicationContext(), "pls fill the empty fields", Toast.LENGTH_SHORT).show();
return false;
} else if (email.getText().toString().matches(emailPattern)) {
//Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
return true;
} else if(!email.getText().toString().matches(emailPattern)) {
Toast.makeText(getApplicationContext(),"Please Enter Valid Email Address",Toast.LENGTH_SHORT).show();
return false;
} else if(number.getText().toString().matches(MobilePattern)) {
Toast.makeText(getApplicationContext(), "phone number is valid", Toast.LENGTH_SHORT).show();
return true;
} else if(!number.getText().toString().matches(MobilePattern)) {
Toast.makeText(getApplicationContext(), "Please enter valid 10 digit phone number", Toast.LENGTH_SHORT).show();
return false;
}
return false;
}
I have used this code above for the validation. The problem I'm facing is in the phone number and email validation, only one validation is working. For example, if I comment out the phone number validation, the email validation is working properly. If I comment out the email validation, the phone number validation is working. If use both validations, it's not working.
For Email Address Validation
private boolean isValidMail(String email) {
String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
return Pattern.compile(EMAIL_STRING).matcher(email).matches();
}
OR
private boolean isValidMail(String email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
For Mobile Validation
For Valid Mobile You need to consider 7 digit to 13 digit because some country have 7 digit mobile number. If your main target is your own country then you can match with the length. Assuming India has 10 digit mobile number. Also we can not check like mobile number must starts with 9 or 8 or anything.
For mobile number I used this two Function:
private boolean isValidMobile(String phone) {
if(!Pattern.matches("[a-zA-Z]+", phone)) {
return phone.length() > 6 && phone.length() <= 13;
}
return false;
}
OR
private boolean isValidMobile(String phone) {
return android.util.Patterns.PHONE.matcher(phone).matches();
}
Use Pattern package in Android to match the input validation for email and phone
Do like
android.util.Patterns.EMAIL_ADDRESS.matcher(input).matches();
android.util.Patterns.PHONE.matcher(input).matches();
Android has build-in patterns for email, phone number, etc, that you can use if you are building for Android API level 8 and above.
private boolean isValidEmail(CharSequence email) {
if (!TextUtils.isEmpty(email)) {
return Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
return false;
}
private boolean isValidPhoneNumber(CharSequence phoneNumber) {
if (!TextUtils.isEmpty(phoneNumber)) {
return Patterns.PHONE.matcher(phoneNumber).matches();
}
return false;
}
Try this
public class Validation {
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
public static final boolean isValidPhoneNumber(CharSequence target) {
if (target.length()!=10) {
return false;
} else {
return android.util.Patterns.PHONE.matcher(target).matches();
}
}
}
He want an elegant and proper solution try this small regex pattern matcher.
This is specifically for India.(First digit can't be zero and and then can be any 9 digits)
return mobile.matches("[1-9][0-9]{9}");
Pattern Breakdown:-
[1-9] matches first digit and checks if number(integer) lies between(inclusive) 1 to 9
[0-9]{9} matches the same thing but {9} tells the pattern that it has to check for upcoming all 9 digits.
Now the {9} part may vary for different countries so you may have array which tells the number of digits allowed in phone number. Some countries also have significance for zero ahead of number, so you may have exception for those and design a separate regex patterns for those countries phone numbers.
in Kotlin you can use Extension function to validate input
// for Email validation
fun String.isValidEmail(): Boolean =
this.isNotEmpty() && Patterns.EMAIL_ADDRESS.matcher(this).matches()
// for Phone validation
fun String.isValidMobile(phone: String): Boolean {
return Patterns.PHONE.matcher(phone).matches()
}
try this:
extMobileNo.addTextChangedListener(new MyTextWatcher(extMobileNo));
private boolean validateMobile() {
String mobile =extMobileNo.getText().toString().trim();
if(mobile.isEmpty()||!isValidMobile(mobile)||extMobileNo.getText().toString().toString().length()<10 || mobile.length()>13 )
{
inputLayoutMobile.setError(getString(R.string.err_msg_mobile));
requestFocus(extMobileNo);
return false;
}
else {
inputLayoutMobile.setErrorEnabled(false);
}
return true;
}
private static boolean isValidMobile(String mobile)
{
return !TextUtils.isEmpty(mobile)&& Patterns.PHONE.matcher(mobile).matches();
}
The built in PHONE pattern matcher does not work in all cases.
So far, this is the best solution I have found to validate a phone number (code in Kotlin, extension of String)
fun String.isValidPhoneNumber() : Boolean {
val patterns = "^\\s*(?:\\+?(\\d{1,3}))?[-. (]*(\\d{3})[-. )]*(\\d{3})[-. ]*(\\d{4})(?: *x(\\d+))?\\s*$"
return Pattern.compile(patterns).matcher(this).matches()
}
//validation class
public class EditTextValidation {
public static boolean isValidText(CharSequence target) {
return target != null && target.length() != 0;
}
public static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
public static boolean isValidPhoneNumber(CharSequence target) {
if (target.length() != 10) {
return false;
} else {
return android.util.Patterns.PHONE.matcher(target).matches();
}
}
//activity or fragment
val userName = registerNameET.text?.trim().toString()
val mobileNo = registerMobileET.text?.trim().toString()
val emailID = registerEmailIDET.text?.trim().toString()
when {
!EditTextValidation.isValidText(userName) -> registerNameET.error = "Please provide name"
!EditTextValidation.isValidEmail(emailID) -> registerEmailIDET.error =
"Please provide email"
!EditTextValidation.isValidPhoneNumber(mobileNo) -> registerMobileET.error =
"Please provide mobile number"
else -> {
showToast("Hello World")
}
}
**Hope it will work for you... It is a working example.
I am always using this methode for Email Validation:
public boolean checkForEmail(Context c, EditText edit) {
String str = edit.getText().toString();
if (android.util.Patterns.EMAIL_ADDRESS.matcher(str).matches()) {
return true;
}
Toast.makeText(c, "Email is not valid...", Toast.LENGTH_LONG).show();
return false;
}
public boolean checkForEmail() {
Context c;
EditText mEtEmail=(EditText)findViewById(R.id.etEmail);
String mStrEmail = mEtEmail.getText().toString();
if (android.util.Patterns.EMAIL_ADDRESS.matcher(mStrEmail).matches()) {
return true;
}
Toast.makeText(this,"Email is not valid", Toast.LENGTH_LONG).show();
return false;
}
public boolean checkForMobile() {
Context c;
EditText mEtMobile=(EditText)findViewById(R.id.etMobile);
String mStrMobile = mEtMobile.getText().toString();
if (android.util.Patterns.PHONE.matcher(mStrMobile).matches()) {
return true;
}
Toast.makeText(this,"Phone No is not valid", Toast.LENGTH_LONG).show();
return false;
}
For check email and phone number you need to do that
public static boolean isValidMobile(String phone) {
boolean check = false;
if (!Pattern.matches("[a-zA-Z]+", phone)) {
if (phone.length() < 9 || phone.length() > 13) {
// if(phone.length() != 10) {
check = false;
// txtPhone.setError("Not Valid Number");
} else {
check = android.util.Patterns.PHONE.matcher(phone).matches();
}
} else {
check = false;
}
return check;
}
public static boolean isEmailValid(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();
return check;
}
String enter_mob_or_email="";//1234567890 or test#gmail.com
if (isValidMobile(enter_mob_or_email)) {// Phone number is valid
}else isEmailValid(enter_mob_or_email){//Email is valid
}else{// Not valid email or phone number
}
XML
<android.support.v7.widget.AppCompatEditText
android:id="#+id/et_email_contact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:maxLines="1"
android:hint="Enter Email or Phone Number"/>
Java
private AppCompatEditText et_email_contact;
private boolean validEmail = false, validPhone = false;
et_email_contact = findViewById(R.id.et_email_contact);
et_email_contact.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String regex = "^[+]?[0-9]{10,13}$";
String emailContact = s.toString();
if (TextUtils.isEmpty(emailContact)) {
Log.e("Validation", "Enter Mobile No or Email");
} else {
if (emailContact.matches(regex)) {
Log.e("Validation", "Valid Mobile No");
validPhone = true;
validEmail = false;
} else if (Patterns.EMAIL_ADDRESS.matcher(emailContact).matches()) {
Log.e("Validation", "Valid Email Address");
validPhone = false;
validEmail = true;
} else {
validPhone = false;
validEmail = false;
Log.e("Validation", "Invalid Mobile No or Email");
}
}
}
});
if (validPhone || validEmail) {
Toast.makeText(this, "Valid Email or Phone no", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "InValid Email or Phone no", Toast.LENGTH_SHORT).show();
}
private fun isValidMobileNumber(s: String): Boolean {
// 1) Begins with 0 or 91
// 2) Then contains 6 or 7 or 8 or 9.
// 3) Then contains 9 digits
val p: Pattern = Pattern.compile("(0|91)?[6-9][0-9]{9}")
// Pattern class contains matcher() method
// to find matching between given number
val m: Matcher = p.matcher(s)
return m.find() && m.group().equals(s)
}
I wrote following code for login but when I type "\" after email-id, it accepts and log in successfully (it doesn't accepts any other symbols or characters only accepts "\").
I don't want that it login with "\".`
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
setContentView(R.layout.main);
WiztangoBaseApplication.InitDialogBox(WiztangoActivity.this);
this.pref = PreferenceManager.getDefaultSharedPreferences(this);
loginStatus = (TextView)findViewById(R.id.login_status);
register = (Button) findViewById(R.id.btnregister);
register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
RegisterIntent();
}
});
login = (Button) findViewById(R.id.btlogin);
password = (EditText) findViewById(R.id.txtPwd);
username = (EditText) findViewById(R.id.txtemail);
saveLoginCheckBox = (CheckBox)findViewById(R.id.saveLoginCheckBox);
pref = getSharedPreferences(Constants.PREFS_NAME,
MODE_PRIVATE);
String usernamestr = pref.getString(Constants.PREF_USERNAME, "");
String passwordsharestr = pref.getString(Constants.PREF_PASSWORD,
"");
username.setText(usernamestr);
password.setText(passwordsharestr);
saveLogin = pref.getBoolean("saveLogin", false);
if (saveLogin == true) {
username.setText(usernamestr);
password.setText(passwordsharestr);
saveLoginCheckBox.setChecked(true);
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
//Constants.clearInfo();
getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE)
.edit()
.putString(Constants.PREF_USERNAME,
username.getText().toString())
.putString(Constants.PREF_PASSWORD,
password.getText().toString())
.putString(Constants.PREF_CHECKED, "TRUE")
.commit();
if (username.getText().toString().trim().equals("")) {
username.setError(Html
.fromHtml("Please Enter Username"));
username.requestFocus();
} else if (password.getText().toString().trim()
.equals("")) {
password.setError(Html
.fromHtml("Please Enter Password"));
password.requestFocus();
} else {
if (Constants
.checkInternetConnection(WiztangoActivity.this)) {
Constants.userpass = password.getText()
.toString();
new AuthenticData().execute();
} else {
WiztangoBaseApplication.ShowThisDialog("Error",
"Please check internet connection.");
}
if (saveLoginCheckBox.isChecked()) {
prefEditor.putBoolean("saveLogin", true);
prefEditor.putString(Constants.PREF_USERNAME,
username.getText().toString());
prefEditor.putString(Constants.PREF_PASSWORD,
password.getText().toString());
saveLoginCheckBox.setChecked(true);
prefEditor.commit();
} else {
SharedPreferences mPreferences = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor=mPreferences.edit();
editor.remove(Constants.PREF_USERNAME);
editor.remove(Constants.PREF_PASSWORD);
editor.commit();
}
}
} catch (Exception e) {
Log.e("Exception In Wiztango/", e.toString());
e.printStackTrace();
}
}
});
} catch (Exception e) {
Log.e("Exception In Wiztango/", e.toString());
e.printStackTrace();
}
}
Inbuilt Patterns Provides Email Validation like:
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(emailStr).matches() && !TextUtils.isEmpty(emailStr)) {
emailEditText.setError("Invalid Email");
emailEditText.requestFocus();
}
Heyy, check this answer here: https://stackoverflow.com/a/7882950/1739882
It says:
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
You can use this code for check is Valid Email or not:
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
Best Approach
Validate email and isEmpty in one method.
public final static boolean isValidEmail(CharSequence target)
{
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
public static boolean isEmailValid(String email) {
boolean isValid = false;
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}
Try out the below method to validate the Email address.
private boolean validateEmail(EditText editText, String p_nullMsg, String p_invalidMsg)
{
boolean m_isValid = false;
try
{
if (p_editText != null)
{
if(validateForNull(editText,p_nullMsg))
{
Pattern m_pattern = Pattern.compile("([\\w\\-]([\\.\\w])+[\\w]+#([\\w\\-]+\\.)+[A-Za-z]{2,4})");
Matcher m_matcher = m_pattern.matcher(editText.getText().toString().trim());
if (!m_matcher.matches() && editText.getText().toString().trim().length() > 0)
{
m_isValid = false;
editText.setError(p_invalidMsg);
}
else
{
m_isValid = true;
}
}
else
{
m_isValid = false;
}
}
else
{
m_isValid = false;
}
}
catch(Throwable p_e)
{
p_e.printStackTrace(); // Error handling if application crashes
}
return m_isValid;
}
Try this code:--
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
I am using following function which uses boolean value.
int recFound=0;
public Boolean CheckUser(String uName,String password)
{
try
{
statement=conn.createStatement();
resultSet=statement.executeQuery("select count(*) from UserMaster where username LIKE'"+uName+"' and password LIKE'"+password+"'");
if(resultSet.getRow()>0)
{
recFound=1;
}
else
{
recFound=0;
}
}
catch (Exception e) {
e.printStackTrace();
recFound=0;
}
if(recFound == 0)
{
return false;
}
else
{
return true;
}
}
I am calling this function through:
boolean isValidUser=con.CheckUser(etLoginID.getText().toString(), etPassword.getText().toString());
if(isValidUser)
{
Intent i= new Intent(getApplicationContext(),Messages.class);
startActivity(i);
}
When i pass this function proper values its not making recFound=1;
And in last condition although recFound==0 it enters in else condition and returns true.
But while assigning this value to caller functions return value it assigns false.
Means it makes , boolean isValidUser=con.CheckUser(etLoginID.getText().toString(), etPassword.getText().toString()); to be false.
isValidUser should get true in such case.
Please help me.
Hi Shrimant Bajirao Peshawe - I,
change the statement "if(resultSet.getRow()>0)" to "if(resultSet. next ())" then try it.
Reference : Refer
you are calling a boolean function in your CheckUser method so its returns true or false value..
Jo just returns true value in that function.
you can also check it with:
if(isValidUser==true)
{
Intent i= new Intent(getApplicationContext(),Messages.class);
startActivity(i);
}
and print a value isValidUser in log that which value it is getting
Try Follwing code...
int recFound = 0;
public boolean CheckUser(String uName, String password) {
try {
statement = conn.createStatement();
resultSet = statement.executeQuery("select count(*) from UserMaster where username LIKE '" + uName + "' and password LIKE '" + password + "'");
if (resultSet.getRow() > 0) {
recFound = 1;
} else {
recFound = 0;
}
if (recFound > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
and
if(con.CheckUser(etLoginID.getText().toString(), etPassword.getText().toString())) {
Intent i= new Intent(getApplicationContext(),Messages.class);
startActivity(i);
}
Change:
if(resultSet.getRow()>0)
{
recFound=1;
}
else
{
recFound=0;
}
to:
if(resultSet.getRow()>0)
{
return true;
}
else
{
return false;
}
Remove conditions checking recFound in catch()
This should solve your problem.
Replace code
if(resultSet.getRow()>0){
recFound=1;
} else {
recFound=0;
}
to
if(resultSet.next()){
return true;
} else {
return false;
}
Try to initialize the
isValidUser to false at the begining
also log the value of resultSet.getRow() and recFound before returning it caller.
you can also try to use cusrsor like below
int recFound=0;
private SQLiteDatabase mDb;
public Boolean CheckUser(String uName,String password)
{
try
{
String sql="select count(*) from UserMaster where username LIKE'"+uName+"' and password LIKE'"+password+"'";
Log.i(TAG,"Executing Query : "+sql);
mCur = mDb.rawQuery(sql, null);
Log.i(TAG,"Query Executed Successfully");
if(mCur!=null)
{
recFound=1;
}
else
{
recFound=0;
}
}
catch (Exception e) {
e.printStackTrace();
recFound=0;
}
if(recFound == 0)
{
return false;
}
else
{
return true;
}
}