I need to re-authenticate the user in order to delete his profile. I've already seen this answer How to re-authenticate a user on Firebase with Google Provider? but it doesn't work for me. In fact this code below eliminates correctly the user only if he has signed in recently. So in my code seems that user.reauthenticate(credential) doesn't work.
public void OnDeleteProfile(View view){
new AlertDialog.Builder(this)
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),null);
user.reauthenticate(credential)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
user.delete()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
});
}
});
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
Related
This is the data being inserted the the correct one is the yay#gmail.com while the incorrectly inserted ones are the ones with a:Name
mAuth.createUserWithEmailAndPassword(email, pass)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Teachers teachers = new Teachers(user, pass, email);
FirebaseDatabase.getInstance().getReference("Teachers")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(teachers).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()) {
Toast.makeText(RegisterTeacher.this, "Teacher has been registered!", Toast.LENGTH_SHORT).show();
Intent i = new Intent(RegisterTeacher.this, TeacherLogin.class);
startActivity(i);
}
else {
Toast.makeText(RegisterTeacher.this, "Failed to register!", Toast.LENGTH_SHORT).show();
}
}
});
} else {
Toast.makeText(RegisterTeacher.this, "Failed to register! Try again!", Toast.LENGTH_SHORT).show();
}
}
});
This code is working fine till public void onSuccess(Void aVoid) but right after its execution, the activity redirects to the previous activity instead of staying on it, and then the toast message appears.
I want it to stay on the activity after registering the user.
mFireBaseAuth = FirebaseAuth.getInstance();
mfirebaseDatabase = FirebaseDatabase.getInstance();
mFireBaseAuth.createUserWithEmailAndPassword(e_mail, password).addOnCompleteListener(StudentSignUp.this, new OnCompleteListener<AuthResult>()
{
#Override
public void onComplete(#NonNull Task<AuthResult> task)
{
if(!task.isSuccessful())
{
Toast.makeText(StudentSignUp.this, "Please check your network or try again using different E-mail.", Toast.LENGTH_SHORT).show();
//loadingBar.dismiss();
}
else
{
StudentDetails studentCredentials = new StudentDetails( studentId, name, e_mail, password );
String uId = task.getResult().getUser().getUid();
mfirebaseDatabase.getReference().child("Student").child(uId).setValue(studentCredentials).addOnSuccessListener(new OnSuccessListener<Void>()
{
#Override
public void onSuccess(Void aVoid)
{
Toast.makeText(StudentSignUp.this, "Your Student is Registered & account has been created.", Toast.LENGTH_SHORT).show();
//loadingBar.dismiss();
}
});
}
}
});
}
Why you need to pass the context in the onCompleteListener.
The code should be like:
mFireBaseAuth.createUserWithEmailAndPassword(e_mail, password).addOnCompleteListener(new OnCompleteListener<AuthResult>()
{
#Override
public void onComplete(#NonNull Task<AuthResult> task)
{
if(!task.isSuccessful())
{
Toast.makeText(StudentSignUp.this, "Please check your network or try again using different E-mail.", Toast.LENGTH_SHORT).show();
//loadingBar.dismiss();
}
else
{
StudentDetails studentCredentials = new StudentDetails( studentId, name, e_mail, password );
String uId = task.getResult().getUser().getUid();
mfirebaseDatabase.getReference().child("Student").child(uId).setValue(studentCredentials).addOnSuccessListener(new OnSuccessListener<Void>()
{
#Override
public void onSuccess(Void aVoid)
{
Toast.makeText(StudentSignUp.this, "Your Student is Registered & account has been created.", Toast.LENGTH_SHORT).show();
//loadingBar.dismiss();
}
});
}
}
});
And instead of using onCompleteListener and then if(!task.isSuccessful()), you can also use onSuccessListener, and sometimes we forget to check if(!task.isSuccessful()) so better use onSuccessListener😀
Feel free to ask if something is unclear. Kindly mark this as the correct answer if it helps you and also in future this answer can help other needy.
My main goal is to delete an account on both Firebase Auth and Firebase Database. I'm using an interface to synchronize the reception of data, a button to delete and a function to return my User.
Initial variables:
FirebaseAuth mAuth = FirebaseAuth.getInstance();
final FirebaseUser mUser = mAuth.getCurrentUser();
DatabaseReference mUserRef = FirebaseDatabase.getInstance().getReference("Users");
The interface:
public interface IMyInterface {
void returnUser(User user);
}
The button to delete User:
btnDeleteAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
readUser(new IMyInterface() {
#Override
public void returnUser(User user) {
String email = user.getEmail();
String password = user.getPassword();
Log.d("EMAIL+PASSWORD", email+password);
AuthCredential credential = EmailAuthProvider
.getCredential(user.getEmail(), user.getPassword());
mUser.reauthenticate(credential).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()) {
mUser.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
mUserRef.child(mUser.getUid()).removeValue();
mAuth.signOut();
finish();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
Toast.makeText(MainActivity.this, "User account deleted!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
});
}
});
And the function to retrieve a User with user informations:
private void readUser(final IMyInterface myCallback) {
mUserRef.child(mUser.getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
user = dataSnapshot.getValue(User.class);
myCallback.returnUser(user);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
So, after calling the button, it calls the function to receive the user informations (email and password) and then it uses both information to delete and log out. The problem is that when the last command inside the button ends, it restarts the button at String email = user.getEmail(), but since it does not have an User instantiated, the getEmail() method returns null and the app crashes.
Why is it returning again the method? Or is there something about synchronization which I'm missing? I do have another button which ends when User info is used and it needs to change activity.
You have this behaviour because you are using addValueEventListener method instead of addListenerForSingleValueEvent. Mosty, both do the same thing but there is a difference, addListenerForSingleValueEvent disconnects straight after getting the data, while addValueEventListener keeps listening.
So to sovle this, use the addListenerForSingleValueEvent method or remove the listener according to the life-cycle of your activity.
Please help i want to retrieve a specific data from the Firebase Realtime database I have 2 users Professor and Student and i want to use that data for validations.
FireBase Realtime Database
firebaseAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if(task.isSuccessful()){
//The task is successful || Task Login
Toast.makeText(getApplicationContext(),"Successfully Login",Toast.LENGTH_LONG).show();
// If the users is professor but if it is student go to userStudent.class
finish();
startActivity(new Intent(getApplicationContext(),userProf.class));
FireBase Realtime Database
This is what you are looking for
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference;
firebaseAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if(task.isSuccessful()){
//The task is successful || Task Login
Toast.makeText(getApplicationContext(),"Successfully Login",Toast.LENGTH_LONG).show();
reference = FirebaseDatabase.getInstance().
getReference("dbname").child(user.getUid());
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String usertype=datas.child("user").getValue().toString();
// If the users is professor but if it is
// student go to userStudent.class
if(usertype.equals("Student")){
startActivity(new
Intent(getApplicationContext(),studentProfile.class));
finish();
}else if (usertype.equals("Professor")) {
startActivity(new
Intent(getApplicationContext(),professorProfile.class));
finish();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Try this code
firebaseAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if(task.isSuccessful()){
//The task is successful || Task Login
Toast.makeText(getApplicationContext(),"Successfully Login",Toast.LENGTH_LONG).show();
//user UID
String userId = task.getResult().getUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child(userId);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String user = dataSnapshot.child("user").getValue(String.class);
if (user.equals("Student")) {
startActivity(new Intent(getApplicationContext(),userStudent.class));
} else if(user.equals("Professor")) {
startActivity(new Intent(getApplicationContext(),userProf.class));
}
finish();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Hope it helps
I know how to create email and password authentication with firebase but that will create only email and id but how do i add name and more detail to that id for instance how I call user.getdisplayname?
Here is my code for creating authentication email and password
bv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog pros=ProgressDialog.show(Register.this,"please wait..","registerring..",true);
mAuth.createUserWithEmailAndPassword(email.getText().toString(),password.getText().toString()).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
pros.dismiss();
if(task.isSuccessful()){
Toast.makeText(Register.this,"sucsseful",Toast.LENGTH_LONG).show();
Intent i=new Intent(Register.this,login.class);
}else {
Log.e("ERROr",task.getException().toString());
Toast.makeText(Register.this,task.getException().getMessage(),Toast.LENGTH_LONG).show();
}
}
});
If you say to create database as well, then how I link it to the user authentication?
private FirebaseUser UserDetaill = FirebaseAuth.getInstance().getCurrentUser() ;
You can use the UserProfileChangeRequest like this
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName("XXX YYYY")
.setPhotoUri(URI)
.build();
UserDetaill.updateProfile(profileUpdates);
USING TASKS
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
.continueWithTask(new Continuation<AuthResult, Task<? extends Object>>() {
#Override
public Task<? extends Object> then(#NonNull Task<AuthResult> task) throws Exception {
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName("XXX YYYY")
.setPhotoUri(URI)
.build();
return task.getResult().getUser().updateProfile(profileUpdates);
}
});