Firebase SignUp always gives an error - android

i am implementing Fire-Base Authentication in my app, With SignUp and SignIn, however i am having a problem, every time i fill the form and click on the SignUp button the Fire-Base gives back an error even though the account was successfully created. My code for the SignUp method:
public class Signup extends AppCompatActivity {
EditText input_email,input_pass;
private FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
//View
input_email = (EditText)findViewById(R.id.id_email);
input_pass = (EditText)findViewById(R.id.id_pass);
//Init Firebase
auth = FirebaseAuth.getInstance();
}
public void iLogin (View v){
startActivity(new Intent(Signup.this, Login.class));
finish();
}
public void iForgot(View v){
//startActivity(new Intent(Signup.this, ForgotPassword.class));
finish();
}
public void iSignUp(View v){
signUpUser(input_email.getText().toString(),input_pass.getText().toString());
}
private void signUpUser(String email, String password) {
auth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful())
{
Toast.makeText(Signup.this, "Successfully created your account", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(Signup.this, "ERROR has occurred", Toast.LENGTH_LONG).show();
}
}
});
}
}
So what happens is:
1- The user Opens the app for the first time, the app opens mainly on the MainActivity.class which then redirects the user to the SignUp.class (The one i have added above).
2- The user then fills two fields: (Email) and (Password) and clicks on the SignUp button
3- The SignUp.class (The one i have added above) then creates a new account and shows the Toast: ERROR has occurred, even though the account has been created successfully. In order for the class to display the correct Toast (Successfully created your account) i need to press on the button a second time.
So just to be clear: The first time you click, the account is created and i can see it in Fire-Base Console but the app still gives the wrong Toast, for it to show the correct one i need to click it again, Any thoughts on what's wrong with the code? Thanks in advance!

Just change:
if(!task.isSuccessful())
to:
if(task.isSuccessful())
and it should work. There is a success when task.isSuccessful() is true, so the ! sign make it false. That's why it works for the second time.

Related

Firebase: How to make one app hides button for another app

I have 2 android apps connected to the same Firebase database, and I want to add a button in the first app to hide another button in the inside the second app.
This is my code on the first app which hides 'btnact' depending on the status of the settings in Remote Config of Firebase:
myconfiguration=FirebaseRemoteConfig.getInstance();
FirebaseRemoteConfigSettings configuratonsettings = new FirebaseRemoteConfigSettings.Builder().build();
myconfiguration.setConfigSettings(configuratonsettings);
Map<String,Object> defaultvalues = new HashMap<>();
defaultvalues.put("btn_enable",false);
myconfiguration.setDefaults(defaultvalues);
fetcher.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myconfiguration.fetch(0).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
myconfiguration.activateFetched();
btnact.setEnabled(myconfiguration.getBoolean("btn_enable"));
}
else
{
Toast.makeText(MainActivity.this, "Something went Wrong\nPlease try again", Toast.LENGTH_SHORT).show();
}
}
});
}
});
I want a way to change this 'btnact' to the id of the button of the other app.. Can anyone have a clue for it?
You can fetch the value of the button you want to hide (boolean value: false or true) inside your second app, then set that button visibility to invisible or gone based on the fetched boolean value.
You can change the value that controls your second app's enabled status/visibility inside your first app.
I don't test this right now, but I think it should work and it is easy to accomplish what you want.

Firebase authentication sign in problem in java

I wrote a login system using Firebase. What I want to do now :
If the user has trouble registering (for example, if he tries to log in with an already registered e-mail), I want to print the error in the warning message and redirect it to the sign-up page.
For this, I have written a code such as below, into register button.
// Sign Up Method
// Kullanıcı Kayıt etme metodu
public void signUp(View view) {
mAuth.createUserWithEmailAndPassword(emailText.getText().toString(),passwordText.getText().toString())
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(signupPage.this, "User Created", Toast.LENGTH_SHORT).show();
Intent homePage = new Intent(signupPage.this, ProfilePage.class);
startActivity(homePage);
finish();
}
}).addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
}).addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (mAuth.getCurrentUser() != null) {
Intent signBack = new Intent(signupPage.this, signupPage.class);
startActivity(signBack);
finish();
}
Toast.makeText(signupPage.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
If there is a problem when User logging in, doing show error message. But it does not redirect to the registration page. Although it shows an error, the user redirects it to the home page as if it were registered successfully.
I would appreciate it if you could help me with this.
Sorry for my bad English.
Well, first you must to know that the onComplete method will be called always, since onFailure only when something fails. So, as I see on your code the app will always launch home.
How to solve?
Just check if the task is successful for redirect to homepage.
In the onComplete method check if all is ok and execute your code with: if (task.isSuccessful)...

Android Firebase Authentication recreates activity forever

I´m using Firebase to register my users and require authentication to go to the home screen implementing the signInWithEmailAndPassword() method and an Intent.
The authentication is working fine, it successfully login my users, BUT the problem is that when the authentication is successful and the HomeActivity starts, the Activity keeps on recreating infinitely and the screen stays black.
I´ve tried many ways of doing the Intent to move from the MainActivity to the HomeActivity after the login but that infinite loop keeps happening.
The weird thing is, if you close the app while the screen is black, "Force Stop" and then open the app again, the app goes to the HomeActivity directly without a problem. The HomeActivity contains a FrameLayout with a Fragment.
I do have the correct Gradle implementation for Firebase.
This is how the MainActivity.java's OnStart() and attemptLogin() look like:
private void attemptLogin() {
String email = Objects.requireNonNull(mEditTextUsername.getText()).toString().trim();
String password = Objects.requireNonNull(mEditTextPassword.getText()).toString().trim();
if (email.isEmpty() || password.isEmpty()) {
mInputLayoutUsername.setError(getString(R.string.error_emptySpace));
mInputLayoutPassword.setError(getString(R.string.error_emptySpace));
return;
}
mProgressBar.setVisibility(View.VISIBLE);
mEnterButton.setVisibility(View.INVISIBLE);
// Use Auth to sign in with email & password
mAuth.signInWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
startActivity(new Intent(MainActivity.this, HomeActivity.class));
finish();
}
});
}
#Override
protected void onStart() {
super.onStart();
mUser = mAuth.getCurrentUser();
if (mUser != null) {
Log.d(TAG, "onCreate: Going home because mUser is not null");
startActivity(new Intent(MainActivity.this, HomeActivity.class));
finish();
}
}
In the Logcat this lines of code repeat forever (Some of them I use them as debug logs, like tha one of the Home has been created and the Fragment)
D/HomeActivity: onCreate: Home has been created
D/HomeActivity: onCreate: Fragment placed correctly
V/FA: Activity resumed, time: 25049213
V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 9
V/FA: Activity paused, time: 25049222
V/FA: onActivityCreated
Inside of the HomeActivity I don't use a recreate() at all.
Thanks for your answers. I hope you can help me make that the app goes directly from the MainActivity into the HomeActivity without it recreating forever
This works fine, it will automatically be redirected to HomeActivity after successful login. If already login then on App Start HomeActivity will start.
private void signIn(String mail, String password) {
mAuth.signInWithEmailAndPassword(mail,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
updateUI();
}
else {
showMessage(task.getException().getMessage());
}
}
});
}
private void updateUI() {
startActivity(HomeActivity);
finish();
}
private void showMessage(String text) {
Toast.makeText(getApplicationContext(),text,Toast.LENGTH_LONG).show();
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser user = mAuth.getCurrentUser();
if(user != null) {
//user is already connected so we need to redirect him to home page
updateUI();
}
}

Unable to mark post's as favorites

Hello everyone I am making an android application with the help of Firebase. The application is working fine but ever since I tried to add the functionality of a favorite button, I am unable to get the bug out of that "add favorite" part of the code.
current_state="not av"
The above part states the current favorite state of the user.
The below code is for "add favorite" part.
Holder.mFavourites.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (current_state.equals("not fav")){
mFav.child(puid).child(kk).child("fav_status").setValue("Added as " +
"fav").addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Holder.mFavourites.setImageDrawable(getContext().getDrawable(R.drawable.ic_star_black));
current_state = "fav";
Toast.makeText(getContext(),"Added to favourites",Toast
.LENGTH_SHORT).show();
}
});
}else if (current_state.equals("fav")){
mFav.child(puid).child(kk).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Holder.mFavourites.setImageDrawable(getContext().getDrawable(R.drawable.ic_star_border_black_24dp));
current_state = "not fav";
Toast.makeText(getContext(),"Removed from favourites",Toast
.LENGTH_SHORT).show();
}
}
});
}
}
});
I am getting a problem with the above code-
1. Whenever the first time user click on the code. He gets added to favourite and if he click again on the same button then he is removed from the favourites, but if the user after clicking once (i.e. after getting added as favourites)goes on and click on the add to fav button again,then the toast of removed from favorites appears regardless of whether the user is in favorites database or not.
Is current_state a class variable that equals "not fav"? Cause it looks like your if statement is just reading a string and doesnt actually know whats going on in the database. What if you query all the favs into an arraylist and test your if statement against the arraylist

Android Firebase Phone Auth Not Receiving SMS Second Time

Hi I am trying to do a phone auth in android using firebase. The first time I install the app the sms comes and verification is successful but subsequently the sms does not come again. I have deleted the user from the auth in firebase and still it is not working.
Following is my code.
MainActivity.java
public class MainActivity extends AppCompatActivity {
CountryCodePicker ccp;
EditText editTextPhone, editTextCode;
FirebaseAuth mAuth;
String codeSent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
editTextCode = findViewById(R.id.editTextCode);
editTextPhone = findViewById(R.id.editTextPhone);
findViewById(R.id.buttonGetVerificationCode).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendVerificationCode();
}
});
findViewById(R.id.buttonSignIn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
verifySignInCode();
}
});
}
private void verifySignInCode() {
String code = editTextCode.getText().toString();
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codeSent, code);
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//here you can open new activity
Toast.makeText(getApplicationContext(),
"Login Successfull", Toast.LENGTH_LONG).show();
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(getApplicationContext(),
"Incorrect Verification Code ", Toast.LENGTH_LONG).show();
}
}
}
});
}
private void sendVerificationCode() {
String phone = editTextPhone.getText().toString();
if (phone.isEmpty()) {
editTextPhone.setError("Phone number is required");
editTextPhone.requestFocus();
return;
}
if (phone.length() < 6 || phone.length() > 13) {
editTextPhone.setError("Please enter a valid phone");
editTextPhone.requestFocus();
return;
}
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phone, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
Toast.makeText(MainActivity.this,
"SMS Sent, Please Wait....", Toast.LENGTH_LONG).show();
editTextCode.requestFocus();
}
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(FirebaseException e) {
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
codeSent = s;
}
};
}
EDIT
restarting the phone allows resending the sms after the 60 second timeout set in the function above. So it seems the phone is keeping something in the memory.
In my case, I have my number on
Phone numbers for testing (optional)
Removing it from there, firebase started sending SMS Code to my number. Spark Plan offer 10k phone auth per month. So that you can test and deploy your app without paying a penny.
In case someone is not getting the concept or reason of not sent sms again then please go through on my below details. I have been confused for very long time that why I didn't get sms for second time, third and so on..
First Read the original documentation:
onVerificationCompleted(PhoneAuthCredential)
This method is called in two situations:
Instant verification: in some cases the phone number can be instantly verified without needing to send or enter a verification
code.
Auto-retrieval: on some devices, Google Play services can automatically detect the incoming verification SMS and perform
verification without user action. (This capability might be
unavailable with some carriers.)
What I found:
onVerificationCompleted:
is only called when instant verification or auto-retrieval occurs.
When you try this for the first time you will get the otp code
from Google but the next time you try it, it can cause instant verification
to get active.
You can do:
So if you are debugging and having problem with not
receiving otp code from google just disable your sim card and enable it
again. This will help you in getting the otp codes from google again for
one more time until you enter your code and instant verification gets
activated again
Please note:
I don't think there is any way you can disable instant
verification as of now. But you can always optimize your code in a way it
doesn't create any problem for you and your users.
If you want to explore more then please check the thread: Click here
You must clear data for this app from phone. If not then run remove app and restart your phone will clear all data related with this app and re-run it.
In my case, I was found the next solution:
You need to update your Google Play Market to the latest version. You can do this in like this: Go to Play Market -> Click on "burger button" -> Select "Settings" in the menu -> Go to the bottom of the menu and you will find "Play Market Version" -> Click into it
Go to Phone Setting -> Go to Applications section -> Select Google Play Settings App -> Clear data\cahce -> then Select Google Play Market App -> Clear data\cahce
Reboot your device after the above steps.
Try again to send SMS to your device.
This solution will help you if you already tried to delete your user from the "White list" in the phone auth section, tried to delete phone number from a user database, and do other tries to fix this issue.

Categories

Resources