Firebase Phone number authentication error, Phone number not readable - android

When I enter a phone number into my EditText field and press login, the java code has to validate if the editText field is empty or not. So after entering my phone no., the if(!phonenumber.isempty()) is always false and the else statement is executed, that is "Please enter number" Toast
Here is my compelete code:
public class User_login extends AppCompatActivity {
private EditText editTextphone;
private Button otp_login;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
otp_login = (Button) findViewById(R.id.otp_login);
editTextphone = (EditText) findViewById(R.id.editTextphone);
String phoneNumber = editTextphone.getText().toString().trim();
mAuth = FirebaseAuth.getInstance();
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
otp_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!phoneNumber.isEmpty()){
if(phoneNumber.length() == 10){
progressBar.setVisibility(View.VISIBLE);
otp_login.setVisibility(View.INVISIBLE);
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber("+91" + phoneNumber)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(User_login.this)
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull #org.jetbrains.annotations.NotNull PhoneAuthCredential phoneAuthCredential) {
progressBar.setVisibility(View.GONE);
otp_login.setVisibility(View.VISIBLE);
}
#Override
public void onVerificationFailed(#NonNull #org.jetbrains.annotations.NotNull FirebaseException e) {
progressBar.setVisibility(View.GONE);
otp_login.setVisibility(View.VISIBLE);
Toast.makeText(User_login.this,"Some error occured" + e.getMessage(), Toast.LENGTH_LONG).show();
}
#Override
public void onCodeSent(#NonNull #org.jetbrains.annotations.NotNull String s, #NonNull #org.jetbrains.annotations.NotNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
Intent intent = new Intent(getApplicationContext(),opt_verify.class);
intent.putExtra("phone", editTextphone.getText().toString());
intent.putExtra("mVerificationId", s);
startActivity(intent);
}
};
}else{
Toast.makeText(User_login.this,"Please enter complete number",Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(User_login.this,"Please enter mobile number",Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onStart() {
super.onStart();
if(mAuth.getCurrentUser() != null){
startActivity(new Intent(this, home_user.class));
}
}
}

You should get the EditText input in the onClick Listner, only then you could get the latest inputted value from the edittext.
ie,
String phoneNumber = editTextphone.getText().toString().trim();
should be called inside :
otp_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneNumber = editTextphone.getText().toString().trim(); //like this
if(!phoneNumber.isEmpty()){

There is a problem in your logic. The reason is that you are getting text before clicking the button meanwhile when the onCreate method runs it gets the value form the EditText. But you need get the value when you click the button each time.
Try this code:
otp_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneNumber = editTextphone.getText().toString().trim();
if (!phoneNumber.isEmpty()) {
if (phoneNumber.length() == 10) {
//you logic or code here
}
}
}
}

Related

Home activity with nav drawer menu does not open after login

I created a Login android app, connected to firebase Real time database and works perfectly (Users has been created successfully).
From LoginActivity, users must go to HomeActivity, which has a navigation drawer menu, but does not work.
I tried to change the activity destination, so after login, I tried to open a TrialActivity and works perfectly.
What could be the problem?
LoginActivity
public class LoginActivity extends AppCompatActivity {
private EditText InputNumber, InputPaswd;
private Button LoginBtn;
private ProgressDialog loadingBar;
private String parentDBName = "Users";
private TextView AdminLink, NotAdminLink;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
InputNumber = (EditText) findViewById(R.id.login_phone_numb_input);
InputPaswd = (EditText) findViewById(R.id.login_Password);
LoginBtn = (Button) findViewById(R.id.login_btn);
loadingBar = new ProgressDialog(this);
AdminLink = (TextView) findViewById(R.id.admin_panel_link);
NotAdminLink = (TextView) findViewById(R.id.not_admin_panel_link);
LoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LoginUser();
}
});
AdminLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LoginBtn.setText("Login Admin");
AdminLink.setVisibility(View.INVISIBLE);
NotAdminLink.setVisibility(View.VISIBLE);
parentDBName="Admins";
}
});
NotAdminLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LoginBtn.setText("Login");
AdminLink.setVisibility(View.VISIBLE);
NotAdminLink.setVisibility(View.INVISIBLE);
parentDBName="Users";
}
});
}
private void LoginUser() {
String phone = InputNumber.getText().toString();
String password = InputPaswd.getText().toString();
// InputNumber.setText("3791881336");
//InputPaswd.setText("1234");
if (TextUtils.isEmpty(phone)) {
Toast.makeText(this,"Please enter your number",Toast.LENGTH_SHORT);
}
else if (TextUtils.isEmpty(password)){
Toast.makeText(this,"Please enter your password",Toast.LENGTH_SHORT);
}
else {
loadingBar.setTitle("Log in");
loadingBar.setMessage("Please wait, loading");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
AllowAccessToAccount( phone, password);
}
}
private void AllowAccessToAccount(String phone, String password) {
final DatabaseReference RootRef;
DatabaseReference reference = FirebaseDatabase.getInstance( "https://ecommerce-bdb44-default-rtdb.europe-west1.firebasedatabase.app").getReference();
RootRef = FirebaseDatabase.getInstance().getReference();
RootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.child(parentDBName).child(phone).exists()){
Users userData = snapshot.child(parentDBName).child(phone).getValue(Users.class);
if (userData.getPhone().equals(phone)){
if (userData.getPassword().equals(password)){
if (parentDBName.equals("Admins")){
Toast.makeText(LoginActivity.this, "Logged in Successfully", Toast.LENGTH_SHORT);
loadingBar.dismiss();
Intent intent = new Intent(LoginActivity.this, AdminActivity.class);
startActivity(intent);
}
else if
(parentDBName.equals("Users")){
Toast.makeText(LoginActivity.this, "Logged in Successfully", Toast.LENGTH_SHORT);
loadingBar.dismiss();
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(intent);
}
}
}
}
else {
Toast.makeText(LoginActivity.this, "Account with" + phone + "do not exist",Toast.LENGTH_SHORT);
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "You need to create an account",Toast.LENGTH_SHORT);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}

login Button redirecting to mainpage instead of user page in android Studio app with firebase realtime database

public class loginActivity extends AppCompatActivity {
TextView signup;
TextInputLayout phone,pass;
Button btn_login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
signup = findViewById(R.id.txt_signup);
phone = findViewById(R.id.phone);
pass = findViewById(R.id.pass);
btn_login = findViewById(R.id.btn_login);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginUser(view);
}
});
}
private boolean validatePhone(){
String p = phone.getEditText().getText().toString();
if(p.isEmpty()){
phone.setError("field is empty!");
return false;
}
else {
phone.setError(null);
phone.setErrorEnabled(false);
return true;
}
}
private boolean validatePass(){
String p = pass.getEditText().getText().toString();
if(p.isEmpty()){
pass.setError("field is empty!");
return false;
}
else {
pass.setError(null);
pass.setErrorEnabled(false);
return true;
}
}
public void loginUser(View v){
if(!validatePhone() | !validatePass()){
return;
}
else {
isUser();
}
}
private void isUser(){
final String appPhone = Objects.requireNonNull(phone.getEditText()).getText().toString().trim();
final String appPass = Objects.requireNonNull(pass.getEditText()).getText().toString().trim();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("users");
Query checkUser = databaseReference.orderByChild("phone").equalTo(appPhone);
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
phone.setError(null);
phone.setErrorEnabled(false);
String fbasePass = dataSnapshot.child("pass").getValue(String.class);
assert fbasePass != null;
if(fbasePass.equals(appPass)){
phone.setError(null);
phone.setErrorEnabled(false);
// String uPhone = dataSnapshot.child(appPhone).child("phone").getValue(String.class);
String uPhone = dataSnapshot.child("phone").getValue(String.class);
String uAadhar = dataSnapshot.child("aadhar").getValue(String.class);
String ucity = dataSnapshot.child("city").getValue(String.class);
String ufname = dataSnapshot.child("fname").getValue(String.class);
String uemail = dataSnapshot.child("email").getValue(String.class);
Intent intent = new Intent(getApplicationContext(),usrHome.class);
intent.putExtra("phone",uPhone);
intent.putExtra("aadhar",uAadhar);
intent.putExtra("city",ucity);
intent.putExtra("fname",ufname);
intent.putExtra("email",uemail);
startActivity(intent);
}
else {
pass.setError("Wrong password");
pass.requestFocus();
}
}
else {
phone.setError("Please Create Account First");
phone.requestFocus();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
when i click login button it is pause for sometime and automatically redirecting to main page of my application.
i was using data from firebase realtime database in login activity.
please help me about this.. i wasted my 2 days to solve this problem but nothing is working.
in case if you have another code that can fulfill this requirement than please let me know.
You are starting the LoginActivity before the Firebase actually logout the user. Try to add a FirebaseAuth.AuthStateListener and just start the LoginActivity when the listener is trigged. See this post: Firebase signout is not leading to the correct activity

java.lang.IllegalArgumentException while authentication using firebase

I am making a Whatsapp like app(By Following tutorial). It crashes when i click on send code button. i confirmed it by try/catch my phone number verification is not working or there's a problem with it
java.lang.IllegalArgumentException: Cannot create PhoneAuthCredential
without either verificationProof, sessionInfo, ortemprary proof.
What i confirmed/tried:
both activities are declared in manifest,
assigned id to layout,
initialized relative argument,
Nothing is there in libs folder of the project,
swapped initialization with layout ,
Tried this code to get value:
String.valueOf(phoneNumberEdt)
I did all what i could as per my level
public class MainActivity extends AppCompatActivity {
private EditText phoneNumberEdt, verificationcodeEdt;
Button sendCodeButton;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallBacks;
String mVerificationId = "0";
//private PhoneAuthProvider.ForceResendingToken mResendToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phoneNumberEdt = (EditText) findViewById(R.id.phonenumber_edt);
verificationcodeEdt = (EditText)
findViewById(R.id.verificationcode_edt);
sendCodeButton = (Button) findViewById(R.id.sendcode_btn);
FirebaseApp.initializeApp(this);
userIsLoggedIn();
phoneNumberEdt.setText("03026989523");
sendCodeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//try{
if(mVerificationId != null)
verifyPhoneNumberWithCode();
else
startPhoneNumberVerification();
/*}catch (Exception e){
Toast toast = Toast.makeText(getApplicationContext(),
"Verification Code is wrong, try again", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER,0,0);
toast.show();
}*/
mCallBacks = new
PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential
phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {}
#Override
public void onCodeSent(String VerificationId,
PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(VerificationId, forceResendingToken);
mVerificationId = VerificationId;
sendCodeButton.setText("Verify Code");
}
};
}
});
}
Error points here
private void startPhoneNumberVerification() {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumberEdt.getText().toString(),//String.valueOf(phoneNumberEdt)
60,
TimeUnit.SECONDS,
this,
mCallBacks);
}
Rest of the functions
private void verifyPhoneNumberWithCode(){
PhoneAuthCredential credential =
PhoneAuthProvider.getCredential(mVerificationId,
verificationcodeEdt.getText().toString());
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential
phoneAuthCredential) {
FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).
addOnComp leteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
userIsLoggedIn();
}
});
}
private void userIsLoggedIn() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null) {
startActivity(new
Intent(getApplicationContext(),MainPageActivity.class));
finish();
return;
}
}

MVP Architecture

I tried to Refactor the Login Module of the Application Any Mistakes and Suggestions what else should i work on and i should keep in mind
Login Presenter.java
public class LoginPresenter implements LoginInteractor.LoginPresenter {
private LoginInteractor.LoginView loginView;
public LoginPresenter(LoginInteractor.LoginView loginView) {
this.loginView = loginView;
}
#Override
public void CheckIdUserVerified(FirebaseUser currentUser, Context context) {
if (currentUser != null) {
if (currentUser.isEmailVerified()) {
loginView.OnLoginSuccess();
}
}
}
#Override
public void Register() {
loginView.OnRegister();
}
#Override
public void Login(String email,String password,final FirebaseAuth mAuth){
if (email.isEmpty() && password.isEmpty()) {
loginView.OnMessage("password is empty");
return;
} else if (email.isEmpty()) {
loginView.OnMessage("email is empty");
return;
} else if (password.isEmpty()) {
loginView.OnMessage("password is empty");
return;
} else {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener((Executor) this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
if (mAuth.getCurrentUser().isEmailVerified()) {
loginView.OnLoginSuccess();
} else {
loginView.builderr("Verify","Verify mo to","Verify");
loginView.OnMessage("Failed");
}
}
}});}}}
Should i Use Firebase on the Model part or its ok if its in View
Login View.java
public class LoginView extends AppCompatActivity implements
LoginInteractor.LoginView {
private LoginPresenter loginPresenter;
public Button login;
public TextView register;
EditText editTextEmail, editTextPassword;
FirebaseAuth mAuth;
FirebaseUser currentUser;
ProgressDialog progressDialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Initialize();
loginPresenter.CheckIdUserVerified(currentUser,this);
//LoginButtonOnClick
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginPresenter.Login(editTextEmail.getText().toString(),
editTextPassword.getText().toString(),mAuth);
}
});
//Goto Register Page
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginPresenter.Register();
}
});
}
#Override
public void Initialize() {
loginPresenter = new LoginPresenter(this);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
login = (Button)findViewById(R.id.buttonLogin);
register = (TextView)findViewById(R.id.registertext);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Logging in..");
progressDialog.setCancelable(false);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
}
public void OnVerify(){
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.google.android.gm");
if (launchIntent != null) {
startActivity(launchIntent);//null pointer check in case package name was not found
} else {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://mail.google.com/mail/#inbox")));
}
}
public void OnRegister(){
startActivity(new Intent(LoginView.this, RegisterView.class));
}
public void OnMessage(String message){
Toast.makeText(LoginView.this, message, Toast.LENGTH_SHORT).show();
}
public void OnLoginSuccess(){
startActivity(new Intent(LoginView.this, MainActivity.class));
finish();
}
public void builderr(String BulderTitle,String BuilderMessage,String
PositiveButton) {
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(BulderTitle);
builder.setMessage(BuilderMessage);
builder.setInverseBackgroundForced(true);
builder.setPositiveButton(PositiveButton,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
OnVerify();
}});
AlertDialog alert = builder.create();
alert.show();
}}
LoginInteractor
public interface LoginInteractor {
interface LoginView{
void Initialize();
void OnLoginSuccess();
void OnMessage(String message);
void OnRegister();
void builderr(String BulderTitle,String BuilderMessage,String
PositiveButton);
}
interface LoginPresenter{
void CheckIdUserVerified(FirebaseUser currentUser, Context context);
void Login(String email, String password, FirebaseAuth mAuth);
void Register();
}
}
**
If i should put firebase on model any idea that will look like?
i was kinda reasearching and looking for answers but how should i initialize firebase without the oncreate Method?**

Junit Testing for an Android Activity

Does any one have any experience with creating unit-test for the On Create and OnClick method in java, using Android Studio? I use data from my Firebasedatabase.
I think I have to use Mock-object, but I don't knot where to start.
Under is the code from my class LoginActivity
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mfireBaseAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference();
mProgressDialog = new ProgressDialog(this);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
buttonSignIn = (Button) findViewById(R.id.buttonSignIn);
textViewSignUp = (TextView) findViewById(R.id.textViewSignUp);
buttonSignIn.setOnClickListener(this);
textViewSignUp.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v == buttonSignIn){
usersignin();
}
if(v==textViewSignUp){
startActivity(new Intent(this, RegisterActivity.class));
}
}
private void usersignin() {
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if(TextUtils.isEmpty(email)){
Toast.makeText(this, "Please enter Email", Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this, "Please enter password", Toast.LENGTH_SHORT).show();
return;
}
mProgressDialog.setMessage("Logging in. Please wait...");
mProgressDialog.show();
mfireBaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
mProgressDialog.dismiss();
if(task.isSuccessful()){
getSignedInUserProfile();
}
}
});
}
private void getSignedInUserProfile() {
DatabaseReference reference = mDatabase;//.child("eduback-2feef");
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
userID = firebaseUser.getUid();
reference.child("Users").child(userID).child("User info").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if(user != null) {
// Save if the user is student or prof in shared prefs.
PreferenceHelper helper = new PreferenceHelper(getBaseContext());
helper.setIsStudent(user.isStudent);
checkStudentOrProfessor(user);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Ups vis error
}
});
}
private void checkStudentOrProfessor(User user) {
Intent i;
if (user.isStudent ) {
i = new Intent(this, MainActivityStudent.class);
} else {
i = new Intent(this, MainActivityProfessor.class);
}
startActivity(i);
}
}
The Mockito mocking framework for Java offers compatibility with Android unit testing.
You can configure mock objects to return some specific value when invoked.
You don't need to test Firebasedatabass.
But you have to make Firebasedatabase wrapper class for yours view
Wrapper class have to include variable(userID, user.isStudent)

Categories

Resources