Edit: problem solved by moving setValue(newProfile) below createUserWithEmailAndPassword method.
I am trying to register people and put their information to database using Firebase in the same activity. There is no problem registering them. But even though user is registered, MainActivity starts and then toast message shows up; setValue() under the same method with these commands doesn't write informations to database. Here is writing to database part (setValue() parameter newProfile is declared as HashMap<>()):
mAuth = FirebaseAuth.getInstance();
firebaseAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null){
databaseReference = FirebaseDatabase.getInstance().getReference().
child(selected_server).child(user_role).child(user.getUid());
databaseReference.setValue(newProfile);
Toast.makeText(Registration.this,"Registration completed!",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Registration.this,MainActivity.class);
startActivity(intent);
finish();
}
}
};
and here is the registration part:
btn_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = et_email.getText().toString();
final String password = et_password.getText().toString();
if(needed_role.equals("") || user_role.equals("") || selected_server.equals("") ) {
Toast.makeText(Registration.this,"Please complete all informations" , Toast.LENGTH_SHORT).show();
}
else{
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(Registration.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
newProfile.put("E-mail" , et_email.getText().toString());
newProfile.put("Password" , et_password.getText().toString());
newProfile.put("Server" , selected_server);
newProfile.put("Summoner Name",et_summoner_name.getText().toString());
newProfile.put("Role", user_role);
newProfile.put("Needed" , needed_role);
if(!task.isSuccessful()){
Toast.makeText(Registration.this,"Sign up error" + task.getException(),Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
Use updateChildren
Make sure you are not using the hashmap before putting value into it
final DatabaseReference databaseRef =FirebaseDatabase.getInstance().getReference().
child(selected_server).child(user_role).child(user.getUid();
databaseRef.updateChildren(newProfile)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
});
Related
This question already has answers here:
Firebase kicks out current user
(19 answers)
Closed 3 years ago.
im devlop an app that has group admin, this group admin can join user by sign them with firebase, and after the admin sign them i want the app will sign back to the admin(the app could have multiple admin- one for each group),
i tried to save the currfirebase user and then switch back but when firebaseauth is change it change automaticlly the pervous user, i even make him final but it didt help
private final FirebaseUser currUser = currUserauth.getCurrentUser();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_contact);
db = FirebaseFirestore.getInstance();
Button addContactBtn = findViewById(R.id.add_contact_btn);
progressBar = findViewById(R.id.add_content_progressbar);
userEmailEt = findViewById(R.id.et_email);
passwordEt = findViewById(R.id.et_password);
confirmBtnEt = findViewById(R.id.confirmBtn);
nameEt = findViewById(R.id.add_contact_name_et);
addContactBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addNewContact();
}
});
}
private void addNewContact() {
progressBar.setVisibility(View.VISIBLE);
final String email = userEmailEt.getText().toString();
String password = passwordEt.getText().toString().trim();
final String name = nameEt.getText().toString();
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches() || email.equals("")) {
userEmailEt.setError("Email is not valid");
} else if (TextUtils.isEmpty(password)) {
passwordEt.setError("password is not valid");
} else if(TextUtils.isEmpty(name)){
nameEt.setError("נא למלא שם");
}else {
mAuth.createUserWithEmailAndPassword(email, password)
.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
FirebaseUser firebaseUser = mAuth.getCurrentUser();
Toast.makeText(getApplicationContext(), "User created successfully", Toast.LENGTH_SHORT).show();
update();
progressBar.setVisibility(View.GONE);
mAuth.signOut();
mAuth.updateCurrentUser(currUser).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
mAuth.getCurrentUser().reload().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Intent intent = new Intent(getApplicationContext(), ContactActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
System.out.println("From addContactActivity: " + mAuth.getCurrentUser().getEmail());
startActivity(intent);
finish();
}
});
User accounts can't create other user accounts in Firebase Authentication on the frontend. Also, only one user can be signed in at a time.
What you're trying to do is best suited to run on a backend you control, using the Firebase Admin SDK to create the user accounts.
I am making an android application using Firebase database and I want to check that the user is not in registered as an "Association" so I am checking if he belongs to the child "Association".
The method userLogin is supposed to not log in the user if he is under the child "Associations" and log in him otherwise.
However, it is not working and the user is logged in even if he is under "Associations"
private void userLogin() {
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
String RegisteredUserID = currentUser.getUid();
DatabaseReference jLoginDatabase = FirebaseDatabase.getInstance().getReference().child("Associations").child(RegisteredUserID);
jLoginDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Toast.makeText(getApplicationContext(), "You are not registered", Toast.LENGTH_SHORT).show();
}
else
{
finish();
Intent intent = new Intent(SignInDonor.this, homedonor.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}});}
else {
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
I did not tried this, but it should work, first, after you log in with a user and enters inside task.isSuccessful , you can retrieve the current logged in user with task.getResult().getUser().getUid(). Then just loop inside Associations and get each user key (I assume that Associations has userIDs inside as nodes with a certain value), then compare if the current logged in user is equal to one inside that node, if matchs it will pop up your Toast, if not you will be redirected.
Try this
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
DatabaseReference jLoginDatabase = FirebaseDatabase.getInstance().getReference().child("Associations");
jLoginDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
if(snapshot.getKey().equals(task.getResult().getUser().getUid()) {
Toast.makeText(getApplicationContext(), "You are not registered", Toast.LENGTH_SHORT).show();
}
else
{
finish();
Intent intent = new Intent(SignInDonor.this, homedonor.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
I used addListenerForSingleValueEvent because we only need to loop once at the reference and not keep listening for data
I'm trying to make a user authentication with Firebase and at the same time store the user Full name and email address in the database linked with the User UID that is created during authentication. Here, my database table name is Users and I have been trying the following code to link my user information with its UID.
With the following code, the user gets registered but no associated database is being formed. What am I doing wrong here? Thanks in advance for the suggestion.
public class SignUpActivity extends AppCompatActivity implements View.OnClickListener {
EditText editTextFullName, editTextEmail, editTextPassword;
private FirebaseAuth mAuth;
FirebaseDatabase database;
DatabaseReference ref;
Users users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
editTextFullName = (EditText) findViewById(R.id.editTextFullName);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
database = FirebaseDatabase.getInstance();
ref = database.getReference("Users");
users = new Users();
mAuth = FirebaseAuth.getInstance();
findViewById(R.id.buttonSignUp).setOnClickListener(this);
}
private void getValues() {
users.setFullName(editTextFullName.getText().toString());
users.setEmail(editTextEmail.getText().toString());
}
private void registerUser() {
final String fullname = editTextFullName.getText().toString().trim();
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
finish();
startActivity(new Intent(SignUpActivity.this, ProfileActivity.class));
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
getValues();
ref.child(""+ user +"").setValue(users);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
if (task.getException() instanceof FirebaseAuthUserCollisionException) {
Toast.makeText(getApplicationContext(), "You are already registered", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonSignUp:
registerUser();
break;
}
}
}
Something like this:
Do not forget the executor class,this is a proper example:
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignupActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(SignupActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
// 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.
if (!task.isSuccessful()) {
Toast.makeText(SignupActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(SignupActivity.this, MainActivity.class));
finish();
}
}
});
}
});
}
you are finishing the activity before it can write to database when you call
finish();
method
fire the intent once the data has been written to database i.e after
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
getValues();
ref.child(""+ user +"").setValue(users);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
startActivity(new Intent(SignUpActivity.this, ProfileActivity.class));
finish();
like this
You don't need value event listener for that you can directly add to database like this :
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("users");
databaseReference.push().setValue(users);
and you have to call finish(); after the database call
Start Activity and call finish() after setting the value to Database as #Rohit has suggested.
One more suggestion is; if you want to save data using UID, you will have to set it in the reference path like below:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users");
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
String UID = user.getUid(); //get UID of currently logged in user(new user in your case)
ref.child(UID).setValue(users); //this will give you expected structure
startActivity(new Intent(SignUpActivity.this, ProfileActivity.class));
finish();
}
User register as student or tutor during registration which saved in firebase database but when login cannot identify the user position which saved in the firebase database so what should I do? Please anyone can give suggestion or advice me how to do this.
The database is save the uid from email authentication as the node under the root then rest details is the children of the uid.
The code like this
private FirebaseAuth auth;
private EditText un, pw;
private String getun, getpw, uid;
private Button bl;
private FirebaseDatabase db;
private DatabaseReference ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
db = FirebaseDatabase.getInstance();
ref = db.getReference();
uid = auth.getCurrentUser().getUid();
ref = db.getReference("users").child(uid);
un = (EditText) findViewById(R.id.Lun);
pw = (EditText) findViewById(R.id.Lpw);
bl = (Button) findViewById(R.id.Lbt);
final TextView rl = (TextView) findViewById(R.id.Lreg);
//login
bl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getun = un.getText().toString().trim();
getpw = pw.getText().toString().trim();
loginaction(getun, getpw);
}
});
//open register page
rl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ri = new Intent(Login.this,Register.class);
Login.this.startActivity(ri);
}
});
}
private void loginaction(String a, String b){
auth.signInWithEmailAndPassword(a, b).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d("Login", "Login Success" + task.isSuccessful());
if (!task.isSuccessful()) {
Log.w("Login", "Login Failed", task.getException());
Toast.makeText(Login.this, "Login Failed. Please try again", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(Login.this, "Login Success", Toast.LENGTH_SHORT).show();
ref.orderByChild("position").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String ps = dataSnapshot.getValue().toString();
if(ps.equalsIgnoreCase("student")){
Intent i = new Intent(Login.this, StudentHomePage.class);
startActivity(i);
}else if (ps.equalsIgnoreCase("tutor")){
Intent i = new Intent(Login.this, TutorHomePage.class);
startActivity(i);
}else{
Toast.makeText(Login.this,
"Wrong input. Please check again the email and password.", Toast.LENGTH_SHORT).show();
return;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
// ...
}
});
}
Create two child nodes from users. One for students and one for tutors.(Give both child values a value of true, otherwise firebase doesn't save the children.)
Have two registration buttons ..one for students and one for tutors. Registration for Tutor code.....
mRegistration.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(DriverLoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()){
Toast.makeText(TutorsLoginActivity.this, "Sign in error", Toast.LENGTH_SHORT).show();
}else{
String user_id= mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db= FirebaseDatabase.getInstance().getReference().child("Users").child("Tutors").child(user_id);
current_user_db.setValue(true);
}
}
});
}
});
Do the same for the students. Just change the .child("Tutors") to .child("Students") This will give you UIDs for the two different groups. And you can do the same when logging in. I think this is a better way to proceed.
I have created an app with the database maintaining in Firebase. I have completed the user registration part and here is the coding I used,
if(edtUsrNameS.length() >0 && edtPassS.length() >0 &&edtEmailS.length() >0) {
strUsrS = edtUsrNameS.getText().toString().trim();
strPassS = edtPassS.getText().toString().trim();
strEmailS = edtEmailS.getText().toString().trim();
if(Constant.isValidEmail(strEmailS)){
edtEmailS.setError(null);
Map<String, String> parameters = new HashMap<>();
parameters.put(Constant.TAG_USER, strUsrS.trim());
parameters.put(Constant.TAG_PASS, strPassS.trim());
parameters.put(Constant.TAG_EMAIL, strEmailS.trim());
String pushId = mFirebaseInstance.getReference(Constant.FIREBASE_LOGIN).getRef().push().getKey();
parameters.put(Constant.TAG_KEY, pushId.trim());
mFirebaseInstance.getReference(Constant.FIREBASE_LOGIN).getRef().child(strUsrS.trim()).setValue(parameters);
Toast.makeText(Login_Reg_Activity.this, "Registered Successfully", Toast.LENGTH_SHORT).show();
finish();
Intent inMain = new Intent(Login_Reg_Activity.this, Login_Reg_Activity.class);
startActivity(inMain);
}else{
edtEmailS.setError("Enter a valid Email");
}
}else{
Toast.makeText(Login_Reg_Activity.this, "Fill all detail", Toast.LENGTH_SHORT).show();
}
After the successful registration, the data are stored in the users table in Firebase like this:
My doubt is that how to login using the credential username and mobile. I have tried by the reference link, but I couldn't succeeded. So, my kind request is to direct me to do this. Also, how to restrict the duplication on user registration?
Thanks in advance.
Step 1:
make sure you have enabled the password login in firebase console as shwon below in the picture
Use Below Code For Login with email and Pwd
FirebaseAuth mAuth = FirebaseAuth.getInstance(); // same auth as you used for regestration process
mAuth.signInWithEmailAndPassword("abc#abc.com","pwd")
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
}
}})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
when you get successfully login than auth change listner will be invoke
Auth Change Listner
private FirebaseAuth.AuthStateListener mAuthListener;
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user !=null){
}
}
};
mAuth.addAuthStateListener(mAuthListener);