Disable Button When EditText Is Empty Android Studio? - java

I'm new, I don't have any experience. I saw some code to disable the login button. I tried to add it to the code. But I did not succeed. The application stops when the login button is pressed when the fields are empty.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityLoginBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
auth = FirebaseAuth.getInstance();
dialog = new ProgressDialog(this);
dialog.setMessage("Logging in...");
if(auth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
binding.submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email, pass;
email = binding.emailBox.getText().toString();
pass = binding.passwordBox.getText().toString();
dialog.show();
auth.signInWithEmailAndPassword(email, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
dialog.dismiss();
if(task.isSuccessful()) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
} else {
Toast.makeText(LoginActivity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
binding.createNewBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, SignupActivity.class));
}
});
}
}

Instead of just checking for the empty fields, you should check for email pattern and for password, you should check if length > 6 otherwise Firebase Auth will throw an exception. Use below code for your submitBtn listener:
binding.submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = binding.emailBox.getText().toString();
String pass = binding.passwordBox.getText().toString();
if (email.isEmpty()) {
binding.emailBox.setError("Email is required");
binding.emailBox.requestFocus();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
binding.emailBox.setError("Email is not valid");
binding.emailBox.requestFocus();
return;
}
if (pass.isEmpty()) {
binding.passwordBox.setError("Password is required");
binding.passwordBox.requestFocus();
return;
}
if (pass.length() < 6) {
binding.passwordBox.setError("Password is weak");
binding.passwordBox.requestFocus();
return;
}
dialog.show();
auth.signInWithEmailAndPassword(email, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
dialog.dismiss();
if(task.isSuccessful()) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
} else {
Toast.makeText(LoginActivity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});

Related

When logging in in login and register modes, leaving the edittexts blank, it kicks them out of the application

I'm new to Android, there are 2 modes in the code I wrote (so we can think of it). When I leave the edittexts blank in the registration section, there is no problem, but when I leave the edittexts blank in the mode I am trying to log in, it throws them out of the application.
step by step:
Step 1: registration mode > leaving e-mail password and username blank, no problem
step 2: login mode > leaving email and password blank will throw an error and kick you out of the app
this is my error message: java.lang.IllegalArgumentException: Given String is empty or null
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_giris);
username = (EditText) findViewById(R.id.kullaniciadi);
password = (EditText) findViewById(R.id.sifre);
eposta = (EditText) findViewById(R.id.eposta);
button = (Button) findViewById(R.id.giris);
login = (TextView) findViewById(R.id.Logininfo);
forgotpas = (TextView) findViewById(R.id.forgotpas);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(eposta.getText().toString().isEmpty() || password.getText().toString().isEmpty()) {
//sign up modu
if(signup && username.getText().toString().isEmpty()){
Toast.makeText(Giris_activity.this, "Invalid input", Toast.LENGTH_SHORT).show();
return;
//eğer eposta ve şifre doğruysa gir---eğer signup modundaysak username de doğruysa gir
}
}
if(signup)
{
handlesignup();
}else
{
handlelogin();
}
}
});
forgotpas.setVisibility(View.GONE);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (signup) {
signup = false;
username.setVisibility(View.GONE);
forgotpas.setVisibility(View.VISIBLE);
button.setText("Log in");
login.setText("Dont have an account? Sign up");
} else {
signup = true;
username.setVisibility(View.VISIBLE);
forgotpas.setVisibility(View.GONE);
button.setText("Sign up");
login.setText("Already have an account? Log in");
}
}
});
forgotpas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openforgotpas();
}
});
}
//-----------------------firebase---------------------------
private void handlesignup() {
FirebaseAuth.getInstance().createUserWithEmailAndPassword(eposta.getText().toString(),password.getText().toString()).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
Toast.makeText(Giris_activity.this, "Signed up successfully, you can login", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(Giris_activity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
private void handlelogin() {
FirebaseAuth.getInstance().signInWithEmailAndPassword(eposta.getText().toString(),password.getText().toString()).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
Toast.makeText(Giris_activity.this, "Logged in successfully", Toast.LENGTH_SHORT).show();
openbaslangic();
}else{
Toast.makeText(Giris_activity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
}```
Modify button click like this
You've to validate before submitting firebase edit text values.
User name optional but when you read it's possible to throw null pointer exception
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(eposta.getText().toString().isEmpty() || password.getText().toString().isEmpty()) {
//sign up modu
return;
}
if(signup && username.getText().toString().isEmpty()){
Toast.makeText(Giris_activity.this, "Invalid input", Toast.LENGTH_SHORT).show();
return;
//eğer eposta ve şifre doğruysa gir---eğer signup modundaysak username de doğruysa gir
}
if(signup){
handlesignup();
}else{
handlelogin();
}
}
});
leaving e-mail password and username blank, no problem
There is no crash because you have a partial validation (although I'm not sure why it works only for one field and only for the signing up proccess)
if (signup && username.getText().toString().isEmpty()) { return; }
leaving email and password blank will throw an error and kick you out of the app
You're not validating any fields here and calling signInWithEmailAndPassword() with empty strings will cause a crash which comes from Firebase SDK.

Firebase Phone authentication only sending OTP For Testing Phone Numbers

I have using Firebase Phone Auth in my project. But the firebase only sending otp for testing phone numbers.
I have added SHA1 and SHA256 in firebase project and enable Android DeviceCheck API. But all time i didn't get otp from Firebase.
When I cheking with testing phone number the otp popup screen is showing up and i am entered otp which i was created verification code ie 123456, 111111, 222222 etc. But otherwise i dont getting otp from firebase.
This is my code
username = findViewById(R.id.username);
fullname = findViewById(R.id.fullname);
mTelephoneNumber = findViewById(R.id.telephonenumberregister);
continueregister = findViewById(R.id.continueregister);
back = findViewById(R.id.back);
txt_login = findViewById(R.id.btnSign);
countryCodePicker = findViewById(R.id.countrycodepicker);
pd = new ProgressDialog(RegisterActivity.this);
pd.setCancelable(false);
auth = FirebaseAuth.getInstance();
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this, StartActivity.class));
}
});
txt_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
continueregister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pd.setMessage("Loading");
pd.show();
mFullTelephoneNumber = countryCodePicker.getSelectedCountryCodeWithPlus() + mTelephoneNumber.getText().toString();
FirebaseDatabase.getInstance().getReference().child("Users").orderByChild("telephoneno").equalTo(mFullTelephoneNumber)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
pd.dismiss();
Toast.makeText(RegisterActivity.this, "There is a user who has this phone number", Toast.LENGTH_SHORT).show();
}
else {
pd.dismiss();
phoneVerification();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
}
private void phoneVerification(){
pd.setMessage("Sending");
pd.show();
AlertDialog dialog;
View verficationView = LayoutInflater.from(RegisterActivity.this).inflate(R.layout.verificationdialoglayout, null);
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setView(verficationView);
builder.setCancelable(false);
dialog = builder.create();
final EditText input_verificationCode = verficationView.findViewById(R.id.mverificationcode);
Button submit = verficationView.findViewById(R.id.submit);
Button resend = verficationView.findViewById(R.id.resend);
TextView countDownView = verficationView.findViewById(R.id.countdown);
ImageButton closeVerification = verficationView.findViewById(R.id.closeverification);
Log.d("a", mFullTelephoneNumber);
CountDownTimer countDownTimer = countDownTimer(countDownView, dialog);
closeVerification.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
countDownTimer.onFinish();
}
});
callbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Log.d("error", e.getMessage());
}
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
Log.d("verificationcode", s);
mVerificationId = s;
resendingToken = forceResendingToken;
pd.dismiss();
dialog.show();
countDownTimer.start();
}
};
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(firebaseAuth)
.setPhoneNumber(mFullTelephoneNumber)
.setCallbacks(callbacks)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(RegisterActivity.this)
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pd.setMessage("Please Wait...");
pd.show();
String str_verificationCode = input_verificationCode.getText().toString();
if (!TextUtils.isEmpty(str_verificationCode) && str_verificationCode.length() == 6){
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, input_verificationCode.getText().toString());
firebaseAuth.signInWithCredential(credential).addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
String userID = task.getResult().getUser().getUid();
String a = "0";
DatabaseReference pref = FirebaseDatabase.getInstance().getReference().child("wallet").child(userID);
HashMap<String, Object> point = new HashMap<>();
point.put("balance", a);
pref.setValue(point);
reference = FirebaseDatabase.getInstance().getReference().child("Users").child(userID);
HashMap<String, Object> map = new HashMap<>();
map.put("id", userID);
map.put("telephoneno", mFullTelephoneNumber);
map.put("username", username.getText().toString().toLowerCase());
map.put("fullname", fullname.getText().toString());
map.put("imageurl", "https://firebasestorage.googleapis.com/v0/b/instagramtest-fcbef.appspot.com/o/placeholder.png?alt=media&token=b09b809d-a5f8-499b-9563-5252262e9a49");
map.put("bio", "");
reference.setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
pd.dismiss();
countDownTimer.onFinish();
}
else {
Toast.makeText(RegisterActivity.this, "error", Toast.LENGTH_SHORT).show();
}
}
});
}
else {
pd.dismiss();
dialog.dismiss();
Toast.makeText(RegisterActivity.this, "Wrong code is entered.", Toast.LENGTH_SHORT).show();
}
}
});
}
else {
Toast.makeText(RegisterActivity.this, "Please enter the code!", Toast.LENGTH_SHORT).show();
}
}
});
resend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
pd.setMessage("Resending");
pd.show();
countDownTimer.onFinish();
countDownTimer.start();
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(firebaseAuth)
.setPhoneNumber(mFullTelephoneNumber)
.setCallbacks(callbacks)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(RegisterActivity.this)
.setForceResendingToken(resendingToken)
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
});
}
private CountDownTimer countDownTimer(TextView countDownView, AlertDialog dialog){
return new CountDownTimer(61000, 1000){
#SuppressLint("SetTextI18n")
#Override
public void onTick(long l) {
countDownView.setVisibility(View.VISIBLE);
countDownView.setText("" + l / 1000);
}
#Override
public void onFinish() {
countDownView.setVisibility(View.GONE);
dialog.dismiss();
}
};
}
}
Please give me a solution.
If anyone is facing this problem, Try to Add SHA fingerprint to your firebase to receive SMS

Direct to each activity according to type of user [duplicate]

This question already has answers here:
How to redirect multiple types of users to their respective Activities?
(3 answers)
Closed 3 years ago.
I have created a project which has two types of user (patient and doctor). During login, I need to retrieve the role attribute in the firebase which under the users table.
In my database structure, user type maybe is "doctor" or "patient". During login, I think I need to retrieve the role information and then assign them to different activity in android studio. However, my code seems doesn't work. The application keeps stopped. Is there anyone can help me. Thanks in advance.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
email = findViewById(R.id.email);
psd = findViewById(R.id.psd);
}
public void clicked(View v) {
switch (v.getId()) {
case R.id.login:
LoginUser();
break;
case R.id.register:
Intent intent = new Intent(this, ChooseRole.class);
startActivity(intent);
break;
}
}
public void LoginUser() {
String email1 = email.getText().toString().trim();
String psd1 = psd.getText().toString().trim();
mAuth.signInWithEmailAndPassword(email1, psd1)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
indentify();
finish();
} else {
Toast.makeText(Login.this, "couldn't login",
Toast.LENGTH_SHORT).show();
}
}
});
}
public void indentify() {
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseDatabase.getInstance().getReference(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long points = dataSnapshot.child("role").getValue(Long.class);
String role = String.valueOf(points);
if(role=="patient"){
Intent intent = new Intent(Login.this, HomePage.class);
startActivity(intent);
}
else{
Intent intent = new Intent(Login.this, HomePage2.class);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
}
Hi guys, I changed it like this and it is successful. Thanks for everyone helping :D
public void LoginUser(){
String email1 = email.getText().toString().trim();
String psd1 = psd.getText().toString().trim();
mAuth.signInWithEmailAndPassword(email1, psd1)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
currentUser = mAuth.getCurrentUser();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseDatabase.getInstance().getReference("users").child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child("role").getValue(String.class).equals("patient")) {
startActivity(new Intent(Login.this, HomePage.class));
return;
}
if (dataSnapshot.child("role").getValue(String.class).equals("doctor")) {
startActivity(new Intent(Login.this, HomePage2.class));
return;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}else {
Toast.makeText(Login.this, "couldn't login",
Toast.LENGTH_SHORT).show();
}
}
});
}
Since in your database you have a node called users, then add a reference to that node, for example:
FirebaseDatabase.getInstance().getReference("users").child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Then do the following:
Change this:
if(role=="patient"){
into this:
if(role.equals("patient")){
You need to use equals() when you want to compare the value of each object.

How to sign in a token using firebase?

In my app there's a signup option, there a user can input his data, after user put input they can get a token, then they can sign in with that token,every user get a unique token and sign in with this unique token.how can I do it with firebase?
Here is the firebase database:
https://i.pinimg.com/originals/40/47/18/404718948df116f257abe31fa8cc98e7.png
Here is the sample code:
public class MainActivity extends AppCompatActivity {
//for sign in
EditText edtUser,edtPwd;
//for sign up
EditText edtNewUser,edtnewPassword,edtnewPhnNum,edtnewEmail;
Button signIn,signUp;
FirebaseDatabase database;
DatabaseReference users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtUser = findViewById(R.id.signinUserEdit);
edtPwd = findViewById(R.id.signinUserPwd);
signIn = findViewById(R.id.signinBtn);
signUp = findViewById(R.id.signUpBtn);
database = FirebaseDatabase.getInstance();
users = database.getReference("Users");
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signUpDilog();
}
});
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signInMethod(edtUser.getText().toString(),edtPwd.getText().toString());
}
});
}
private void signInMethod(final String user, final String pwd) {
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(user).exists()){
if (!user.isEmpty()){
SignInUpModel login = dataSnapshot.child(user).getValue(SignInUpModel.class);
if (login.getPassword().equals(pwd)){
Toast.makeText(MainActivity.this,"Login ok!",Toast.LENGTH_LONG).show();
Intent home = new Intent(MainActivity.this,HomeActivity.class);
CommonModel.currentUser = login;
startActivity(home);
finish();
}
else
Toast.makeText(MainActivity.this,"Wrong Password",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this,"Please enter your user name",Toast.LENGTH_LONG).show();
}
}
else
Toast.makeText(MainActivity.this,"User is not exists",Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void signUpDilog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("Sign Up");
alertDialog.setMessage("Please fill your information");
LayoutInflater inflater = this.getLayoutInflater();
View signUpLayout = inflater.inflate(R.layout.signuplayout,null);
edtNewUser = signUpLayout.findViewById(R.id.signUpEdit);
edtnewEmail = signUpLayout.findViewById(R.id.signoutemailEdit);
edtnewPhnNum = signUpLayout.findViewById(R.id.signupphnEdit);
edtnewPassword = signUpLayout.findViewById(R.id.signUpPwd);
alertDialog.setView(signUpLayout);
alertDialog.setIcon(R.drawable.ic_account_circle_black_24dp);
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final SignInUpModel user = new SignInUpModel(edtNewUser.getText().toString(),edtnewEmail.getText().toString(),
edtnewPhnNum.getText().toString(),edtnewPassword.getText().toString());
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(user.getUserName()).exists()){
Toast.makeText(MainActivity.this,"User already exists",Toast.LENGTH_LONG).show();
}else{
users.child(user.getUserName()).setValue(user);
Toast.makeText(MainActivity.this,"User registration success!",Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
dialogInterface.dismiss();
}
});
alertDialog.show();
}
}
I expect when the user put his/her details and complete signup then he/she gets a token and put this token and complete his signing and goes to the next activity. How can I do that using firebase? thank u
Try this for SignUp
TextView mailSignup = findViewById(R.id.mailSignup);
String Email = mailSignup.getText().toString();
TextView passwordSignup = findViewById(R.id.passwordSignup);
String Password = passwordSignup.getText().toString();
TextView nameSignup = findViewById(R.id.nameSignup);
String Name = nameSignup.getText().toString();
TextView ErrorText = findViewById(R.id.errortext);
TextView confirmPassSignup = findViewById(R.id.confirmpassSignup);
String Verification = confirmPassSignup.getText().toString();
if (!(Password.isEmpty()) && !(Email.isEmpty()) && !(Name.isEmpty()) && Password.equals(Verification) && Password.length() > 5) {
mAuth = FirebaseAuth.getInstance();
mAuth.createUserWithEmailAndPassword(Email, Password).addOnCompleteListener(SignUp.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
mDatabase = FirebaseDatabase.getInstance().getReference("users");
String UserUid = mAuth.getCurrentUser().getUid();
user User = new user(UserUid,Name,Email);
mDatabase.child(UserUid).setValue(User);
// Toast.makeText(SignUp.this, "Save Done", Toast.LENGTH_SHORT).show();
} else {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
progressDialog.dismiss();
}
}, 1000);
// If sign in fails, display a message to the user.
Toast.makeText(SignUp.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
And this for Login
EditText mailLogin = findViewById(R.id.mailLogin);
String Email = mailLogin.getText().toString();
EditText passwordLogin = findViewById(R.id.passwordLogin);
String Password = passwordLogin.getText().toString();
if (!(Email.isEmpty()) && !(Password.isEmpty())){
mAuth.signInWithEmailAndPassword(Email,Password)
.addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Intent goToHome = new Intent(LoginActivity.this, Home.class);
startActivity(goToHome);
}
else{
Toast.makeText(getApplicationContext(),"Wrong Credentials",Toast.LENGTH_LONG).show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
}
}, 1000);
}
}
});
}
}

Applications stops its work when TextView is empty. How can I fix it?

I have a loginActivity class. that does email and password validation and checks if a login field is empty.
the problem is that my application stops if the login fields are empty.
Here's my code :
Validators :
private boolean validatePassword() {
boolean password1 = password.getText().toString().trim().isEmpty();
String password2 = password.getText().toString().trim();
if (password1) {
password.setError("Поле не должно быть пустым");
return false;
} else if (!PASSWORD_PATTERN.matcher(password2).matches()) {
password.setError("Слабый пароль. ");
return false;
} else {
password.setError(null);
return true;
}
}
private boolean validateEmail() {
String email1 = email.getText().toString().trim();
if (email1.isEmpty()) {
email.setError("Поле не должно быть пустым");
return false;
} else if (!Patterns.EMAIL_ADDRESS.matcher(email1).matches()) {
email.setError("Введите правильный E-mail");
return false;
} else {
email.setError(null);
return true;
}
}
Registeration :
public void register(final String email, final String password) {
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (validateEmail() & validatePassword()) {
if (task.isSuccessful()) {
Toast.makeText(LogInActivity.this, "Successfully", Toast.LENGTH_SHORT).show();
} else Toast.makeText(LogInActivity.this, "Failed", Toast.LENGTH_SHORT).show();
} else if (email.isEmpty() || password.isEmpty())
Toast.makeText(LogInActivity.this, "Поля не должно быть пустыми", Toast.LENGTH_SHORT).show();
}
});
}
Login :
public void logIn(final String email, final String password) {
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (checkBox.isChecked()) {
if (validateEmail()) {
if (task.isSuccessful()) {
Toast.makeText(LogInActivity.this, "Successfully", Toast.LENGTH_SHORT).show();
startNewActivity();
} else
Toast.makeText(LogInActivity.this, "Failed", Toast.LENGTH_SHORT).show();
} else if (email.isEmpty() || password.isEmpty())
Toast.makeText(LogInActivity.this, "Проверьте введенные данные", Toast.LENGTH_SHORT).show();
;
}
}
});
}
Changing activity :
private void startNewActivity() {
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
this.finish();
}
I am unable to find an error in your code because you didn't post any logcat error message but I worked on something similar and it works perfectly for me, just change my fields like editTextPassword, editTextEmail and also in intents with your fields and you are good too go.
private void userLogin() {
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if (email.isEmpty()) {
editTextEmail.setError("Email is required");
editTextEmail.requestFocus();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
editTextEmail.setError("Please enter a valid email");
editTextEmail.requestFocus();
return;
}
if (password.isEmpty()) {
editTextPassword.setError("Password is required");
editTextPassword.requestFocus();
return;
}
if (password.length() < 6) {
editTextPassword.setError("Minimum lenght of password should be 6");
editTextPassword.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
finish();
Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
you just have to call this function when the user clicks on login button.
Button loginButton = (Button)findViewById(R.id.buttonLogin);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userLogin();
}
});

Categories