This question already has answers here:
Android auth firebase error: Local module descriptor class for com.google.firebase.auth not found
(5 answers)
Closed 3 years ago.
I'm creating an apps for my final year project. So i want to use login and signup features. But when i enter the details of the signup, its keep fail and do not direct the data to the firebase.
Signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validate()){
String Email = email.getText().toString().trim();
String Password = password.getText().toString().trim();
firebase.createUserWithEmailAndPassword(Email, Password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(Signup.this, "Signup successful", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Signup.this, LoginPage.class));
}
else
{
Toast.makeText(Signup.this, "Signup failed", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
So, is there anything that i have to change?
make sure to initialize the FirebaseAuth object
FirebaseAuth firebase = FirebaseAuth.getInstance();
and Enable the email method in Firebase console
Make sure that you enabled email as an authentication method on firebase portal authentication section.
Related
This question already has answers here:
How to redirect multiple types of users to their respective Activities?
(3 answers)
Checking if a particular value exists in the Firebase database
(6 answers)
Closed 2 years ago.
First, I will tell the flow of my App.
Login Screen(SignInActivity.java) -> Enter details(MainActivity.java) ->Home Screen(HomeScreenActivity.java)
In my app, I have used Firebase Authentication and Firebase Database. When the user is new, then it should go to Main Activity from SignInActivity where user enters his name, a short description and his hobby. The details are stored in Firebase Database and then HomeScreenActivity opens where user details are shown in Recycler View.
But currently what happens is when same user does login again, it again asks user for details. I want to check if users Google Account already exists in Firebase Auth, then instead of asking details, it should directly go to HomeScreenActivity.
I checked many answers on StackOverflow, but nothing seems to work. One thing that i tried was additionalUserInfo.isNewUser but in this app crashes when user does login again, showing null error where I display user details in HomeScreenActivity.
SignInActivity.java
private void firebaseAuthWithGoogle(String idToken) {
AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
mAuthIn.signInWithCredential(credential)
.addOnCompleteListener(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
Log.d(TAG, "SignInWithCredential:success");
startActivity(new Intent(SignInActivity.this, MainActivity.class));
finish();
} else {
// If sign in fails, display a message to the user.
Toast.makeText(SignInActivity.this, "Authentication Failed", Toast.LENGTH_SHORT).show();
}
}
});
}
MainActivity.java
public void init() {
hobbiesContinueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name=user.getText().toString().trim();
String desc=description.getText().toString().trim();
String hobby=spinner.getSelectedItem().toString();
String image="default";
String thumbnail="default";
if(!TextUtils.isEmpty(name))
{
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
assert currentUser != null;
String userId=currentUser.getUid();
User user=new User(name,hobby,desc,image,thumbnail);
dbRef.child(userId).setValue(user);
startActivity(new Intent(getApplicationContext(), HomeScreenActivity.class));
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Enter a name",Toast.LENGTH_SHORT).show();
}
}
});
}
HomeScreenActivity.java
dbRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
imgvw = headerView.findViewById(R.id.imageView);
imgvw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//to open gallery
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICK);
}
});
TextView nameDrawer = findViewById(R.id.navName);
TextView descDrawer = findViewById(R.id.navDescription);
User change = snapshot.getValue(User.class);
assert change != null;
//This is where null error occurs
nameDrawer.setText(change.getUserName());
descDrawer.setText(change.getUserDesc());
//change profile picture
image= Objects.requireNonNull(snapshot.child("userImage").getValue()).toString();
Log.d(TAG, "onComplete: "+image);
if(!image.equals("default")){
Picasso.get().load(image).placeholder(R.drawable.avatar).into(imgvw);
}
}
The solution is to save your user details in shared preferences for the first time when the user sign in , then after the user signs out and sign it again , you get data from shared preferences and set them directly to your edittexts
Try this Code :
///save sharedpreferences
SharedPreferences sharedPreferences =
getSharedPreferences("prefs",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username","put here your username"); //
editor.putString("email","put your email here"); //you can add more details
editor.apply();
///get sharedpreferences
SharedPreferences sharedPreferences1 =
getSharedPreferences("prefs",Context.MODE_PRIVATE);
String username = sharedPreferences1.getString("username","");
String email = sharedPreferences1.getString("email","");
//then here set the valeus from sharedpreferences to your edittexts
This question already has answers here:
One time login in app - FirebaseAuth
(3 answers)
Closed 3 years ago.
I have an application there is user login screen sends to an activity if logging action is OK. But everytime I closed the application, app asks for email and password, I want to stay logged in like instagram or facebook. Have can I do that? And also how can I do that, do I have to change the code in signin activity or create another class for saving the current user, I am so much confused. There is my login code for firebase:
SignInActivity;
public class SignInActivity extends AppCompatActivity {
private EditText SignInMail, SignInPass;
private FirebaseAuth auth;
private Button SignInButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
// set the view now
setContentView(R.layout.activity_signin);
SignInMail = (EditText) findViewById(R.id.SignInMail);
SignInPass = (EditText) findViewById(R.id.SignInPass);
SignInButton = (Button) findViewById(R.id.SignInButton);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
SignInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = SignInMail.getText().toString();
final String password = SignInPass.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Mail", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Password", Toast.LENGTH_SHORT).show();
return;
}
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(SignInActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
// progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 8) {
Toast.makeText(getApplicationContext(),"pass min 8",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_SHORT).show();
}
} else {
Intent intent = new Intent(SignInActivity.this, CampaignActivity.class);
startActivity(intent);
finish();
}
}
});
}
});
}
public void NavigateSignUp(View v) {
Intent inent = new Intent(this, SignupActivity.class);
startActivity(inent);
}
public void NavigateForgetMyPassword(View v) {
Intent inent = new Intent(this, ResetPasswordActivity.class);
startActivity(inent);
}
}
In the onCreate function, you need to add this piece of code
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
This code will fetch you the currently logged in user if the user has previously signed in, else will return null.
Check this link for further understanding.
Get the currently signed-in user - Firebase Docs
I hope this solved your problem. If you feel this answer is correct, please accept the answer.
When a user logged in successfully store the LOGIN TYPE of User SharedPreferenceence and check that flag again when user restart app. If Shared Preference contains value then just take him to Main Screen.
Like this on each login update this value and check
PreferencesManager.getInstance().getString(ANNONYMOUS_SIGNUP_DATE, "")) && (PreferencesManager.getInstance().getInt(LOGIN_TYPE, 0) == LOGIN_TYPE_ANNONYMOUS)
Since you authenticated the user, then you can create a splash screen before your sign in activity, and write the following code:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null){
Intent i = new Intent(SplashActivity.this, HomeActivity.class);
} else{
Intent i = new Intent(SplashActivity.this, SignInActivity.class);
}
Here, you check if currently there is a logged in user and then navigate to the right activity according to the condition.
I would recommend you to use splash screen first and check it user is logged in by the following
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// User is signed in
// go to main page
} else {
// No user is signed in
// go to loging page
}
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 3 types of user
parents, teacher, admin,
I have already made login activity
and for parent and they will provide email and password and when firebase authenticate it. and when successful it will go to parents activity
And i want to make activity for admin to add and register/signup parents
and they still provide email and pass to my login activity and will be directly to the new admin activity after authenticated by firebase
what changes will do to my login
public class Login extends AppCompatActivity implements View.OnClickListener {
private EditText editTextEmail;
private EditText editTextPassword;
private Button Login;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
FirebaseApp.initializeApp(this);
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser() != null) {
// profile activity
finish();
startActivity(new Intent(getApplicationContext(), Parent_Home.class));
}
editTextEmail = findViewById(R.id.input_username);
editTextPassword = findViewById(R.id.input_password);
findViewById(R.id.btn_login).setOnClickListener(this);
progressDialog = new ProgressDialog(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_login: {
userLogin();
break;
}
}
}
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 valid email");
editTextEmail.requestFocus();
return;
}
if (password.isEmpty()) {
editTextPassword.setError("Password is required");
editTextPassword.requestFocus();
return;
}
if (password.length()<6 ){
editTextPassword.setError("Minimum of length of password should be 6");
editTextPassword.requestFocus();
return;
}
//if the email&pass is not empty
//display dialog
progressDialog.setMessage("Please Wait...");
progressDialog.show();
firebaseAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new
OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (task.isSuccessful()) {
//start profile/ menu activity
finish();
SharedPrefs.saveSharedSetting(Login.this, "CaptainCode", "false");
startActivity(new Intent(getApplicationContext(), Parent_Home.class));
} else {
Toast.makeText(Login.this, "Error", Toast.LENGTH_SHORT).show();
}
}
});
}
}
//Todo: add back confirmation
In sign up process add additional object in your database for every user, for example you can call it a type. So when someone sign up to your app make him choose which type of account he is creating (or maybe you already have this), so object will contain info what account is created: parent or teacher or admin. For example: type: "teacher"
After login return data from database for user who just logged in and check what is the type of his account and according to type value (parent, teacher, admin) you will know who logged in in your app and you can start corresponding screen.
I am trying to implement google sign-in feature in my app. I have followed this documentation, problem is - if I use previously used google account, it is not showing an error like "the e-mail is already registered in this app". As a result, previously stored data with the account are deleted & the google account is registered again. Here is my code :
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(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
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
int coins = 100;
String name, email;
name = user.getDisplayName();
email = user.getEmail();
//updateUI(user);
storeUserCredentials(name, email, coins);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(SignUpActivity.this, "Error : " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
public void storeUserCredentials(String name, String email, int coins){
progressBar.setVisibility(View.VISIBLE);
User user = new User(name, email, coins);
mDatabase.getReference("Users")
.child(mAuth.getCurrentUser().getUid())
.setValue(user)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()){
Toast.makeText(SignUpActivity.this, "Registration Successful!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(SignUpActivity.this, MainActivity.class));
finish();
} else {
if (task.getException() instanceof FirebaseAuthUserCollisionException){
Toast.makeText(SignUpActivity.this, "The email is already used", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(SignUpActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
});
}
What is wrong with my code, please explain.
When you call signInWithCredential the SDK returns a task that successfully completes when the user is signed in. Since you call storeUserCredentials on that condition, it will get called each time the user is signed in. This is actually a quite normal flow.
If you want to detect if this account is new to Firebase Authentication, you can check the creation time of the user. See Firebase Auth, how to know new user signed up, rather than existing user sign in?
If you want to detect whether you've already seen the user before, you'll want to check in the database before calling storeUserCredentials. But what you now have is a pretty idiomatic flow, since it for example ensures you store the up-to-date display name each time you ask the user to sign in.
When users signup using the Firebase Email/Password SIGN-IN METHOD in android, how can we verify their Emails ?
For Android Email verification, first you can view the documentation by firebase here.
Send a user a verification email
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Email Sent.");
}
}
});
In my App whenever a user registers, sendEmailVerification(); is triggered
private void sendEmailVerification() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Email verification sent.");
}
}
});
}
Using the previous method, your users will now be provided with a verification Email. And it will look something a lot like this
Did they verify their email ?
private void IsEmailVerified() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user.isEmailVerified()) {
Log.d(TAG, "Email is verified.");
} else {
Log.d(TAG, "Email is not verified !.");
}
}
Sadly, you may not customize the content/body of your verification Email ( I have been heavily corresponding with Firebase to provide alternative less hideous looking templates ). You may change the title or the message sender ID, but that's all there is to it.
Not unless you relink your application with your own supported Web. Here.