Android firebase create and display username - android

I am using Firebase user sign up method with email and password. While creating a new user I also store information such username that later on needs to be displayed in app profile page.
How could I retrieve the username of currently logged in person ?
Thank you in advance
private void registration(){
final String email = Email.getText().toString().toString().trim();
final String password = Password.getText().toString().trim();
final String username = Username.getText().toString().trim();
final String age = Age.getText().toString().trim();
final String userID = userAuth.getCurrentUser().getUid();
if (!TextUtils.isEmpty(email)&& !TextUtils.isEmpty(password)&& !TextUtils.isEmpty(username)&& !TextUtils.isEmpty(age)){
showProgress.setMessage("Registration in progress...");
showProgress.show();
userAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
String user_id = userAuth.getCurrentUser().getUid();
DatabaseReference current_user_db = DatbaseOfUsers.child(user_id);
current_user_db.child("email").setValue(email);
current_user_db.child("username").setValue(username);
current_user_db.child("Age").setValue(age);
current_user_db.child("uID").setValue(userID);
showProgress.dismiss();
//After user is created main screen intent is called
Intent mainpage = new Intent(RegisterActivity.this, MainPageActivity.class);
mainpage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainpage);
}
else if(!task.isSuccessful()){
showProgress.dismiss();
Toast.makeText(RegisterActivity.this,"Error While Register",Toast.LENGTH_LONG).show();
}
}
});
}
else{
showProgress.dismiss();
Toast.makeText(RegisterActivity.this,"Please Enter All Required Fields",Toast.LENGTH_LONG).show();
}

private FirebaseAuth mAuth;
mAuth = FirebaseAuth.getInstance();
final FirebaseUser Theuser = mAuth.getCurrentUser();
if (Theuser !=null)
_UID = Theuser.getUid();

You can send request to Users with current user's uid.
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("Users").orderByChild(currentUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
In onDataChange returns value you are looking as dataSnapshot. Then cast it to your model, get the want ever you want.

Related

Firebase Database paths must not contain '.', '#', '$', '[', or ']'

Hello I'm with this error and I'm trying to capture and write about the user's node> email doing so but still giving error, could someone help me? any help is welcome.
the node email already has the comma but when it comes to recovering I still get the error I'm trying to modify the node when receiving with the code below.
my code
addButton.setOnClickListener(new View.OnClickListener() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
#Override
public void onClick(View v) {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
final String userUid = user.getEmail();
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("users").child(user.getEmail().replace(".",",")).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String,Object> map = new HashMap<>();
map.put("cassinotime",dataSnapshot.child("cassinotime").getValue(String.class));
map.put("cassinoprofit",dataSnapshot.child("cassinoprofit").getValue(String.class));
ref.child("users").child(user.getEmail()).child("cassino").child("cassinotime").setValue(map);
ref.child("users").child(user.getEmail()).child("cassino").child("cassinotime").setValue("50000");
ref.child("users").child(user.getEmail()).child("cassino").child("cassinoprofit").setValue("250");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
register code
private void firebaseAuthWithGoogle(final GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
User user = new User(
);
String photoUrl = null;
if (account.getPhotoUrl() != null) {
user.setPhotoUrl(account.getPhotoUrl().toString());
}
user.setEmail(account.getEmail());
user.setUser(account.getDisplayName());
user.setUid(mAuth.getCurrentUser().getUid());
user.setMoney(money);
user.setCassinotime(cassinotime);
user.setCassinoprofit(cassinoprofit);
FirebaseUtils.getUserRef(account.getEmail().replace(".", ","))
.setValue(user, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
mFirebaseUser = mAuth.getCurrentUser();
finish();
}
});
} else {
dismissProgressDialog();
}
}
});
Instead of using the email as a parent node for the user's details, it is better to use the userId:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userId = user.getUid();
ref.child("users").child(userId).addListenerForSingleValueEvent(/* ... */);
While storing email as a path, I recommend you to encode the email i.e., replace 'dots' from 'commas'. If you want to retrieve, you can decode.
public static String decodeString(String string) {
return string.replace(",", ".");
}
In these three lines of code:
ref.child("users").child(user.getEmail()).child("cassino").child("cassinotime").setValue(map);
ref.child("users").child(user.getEmail()).child("cassino").child("cassinotime").setValue("50000");
ref.child("users").child(user.getEmail()).child("cassino").child("cassinoprofit").setValue("250");
You are still using the original user.getEmail() value. You should use the encoded string like you did in the query. Just do it once and store it in a variable, then reuse the variable.
Even better, just make the reference once and reuse it:
final DatabaseReference ref = FirebaseDatabase.getInstance()
.getReference()
.child("user")
.child(user.getEmail().replace(".",","));
Then in the callback:
ref.child("cassino").child("cassinotime").setValue(map);
ref.child("cassino").child("cassinotime").setValue("50000");
ref.child("cassino").child("cassinoprofit").setValue("250");

Unable to add user details on Firebase RealTime Database

I am currently trying to add user details who have registered in my app using Firebase Phone authentication to Firebase Real time database. I am successfully able to verify a user, but I am not able to send to Details Activity class where I need the user to enter his details, instead I jump to MainActivity Directly.
I do get Toast "Phone Verified" whenever I add a new user.
Register.java
public class Register extends AppCompatActivity {
FirebaseAuth auth;
String phoneNumber;
String otpCode;
String verificationId;
EditText phone, optEnter;
Button next;
CountryCodePicker countryCodePicker;
PhoneAuthCredential credential;
Boolean verificationOnProgress = false;
ProgressBar progressBar;
TextView state, resend;
PhoneAuthProvider.ForceResendingToken token;
//FirebaseFirestore fStore;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
phone = findViewById(R.id.phone);
optEnter = findViewById(R.id.codeEnter);
countryCodePicker = findViewById(R.id.ccp);
next = findViewById(R.id.nextBtn);
auth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressBar);
state = findViewById(R.id.state);
resend = findViewById(R.id.resendOtpBtn);
resend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// todo:: resend OTP
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!phone.getText().toString().isEmpty() && phone.getText().toString().length() == 10) {
if (!verificationOnProgress) {
next.setEnabled(false);
progressBar.setVisibility(View.VISIBLE);
state.setVisibility(View.VISIBLE);
String phoneNum = "+" + countryCodePicker.getSelectedCountryCode() + phone.getText().toString();
Log.d("phone", "Phone No.: " + phoneNum);
requestPhoneAuth(phoneNum);
} else {
next.setEnabled(false);
optEnter.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
state.setText("Logging in");
state.setVisibility(View.VISIBLE);
otpCode = optEnter.getText().toString();
if (otpCode.isEmpty()) {
optEnter.setError("Required");
return;
}
credential = PhoneAuthProvider.getCredential(verificationId, otpCode);
verifyAuth(credential);
}
} else {
phone.setError("Valid Phone Required");
}
}
});
}
private void requestPhoneAuth(String phoneNumber) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(phoneNumber, 60L, TimeUnit.SECONDS, this,
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeAutoRetrievalTimeOut(String s) {
super.onCodeAutoRetrievalTimeOut(s);
Toast.makeText(Register.this, "OTP Timeout, Please Re-generate the OTP Again.", Toast.LENGTH_SHORT).show();
resend.setVisibility(View.VISIBLE);
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
token = forceResendingToken;
verificationOnProgress = true;
progressBar.setVisibility(View.GONE);
state.setVisibility(View.GONE);
next.setText("Verify");
next.setEnabled(true);
optEnter.setVisibility(View.VISIBLE);
}
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
verifyAuth(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(Register.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void verifyAuth(PhoneAuthCredential credential) {
auth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(Register.this, "Phone Verified", Toast.LENGTH_SHORT).show();
checkUserProfile();
} else {
progressBar.setVisibility(View.GONE);
state.setVisibility(View.GONE);
Toast.makeText(Register.this, "Can not Verify phone and Create Account.", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onStart() {
super.onStart();
if (auth.getCurrentUser() != null) {
progressBar.setVisibility(View.VISIBLE);
state.setText("Logging IN");
state.setVisibility(View.VISIBLE);
checkUserProfile();
}
}
private void checkUserProfile() {
FirebaseUser firebaseUser = auth.getCurrentUser();
assert firebaseUser != null;
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
if (userid != null) {
Intent intent = new Intent(Register.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(Register.this, "Profile doesnt exist", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Register.this, Details.class);
startActivity(intent);
}
}
}
Details.java
public class Details extends AppCompatActivity {
public static final String TAG = "TAG";
EditText firstName,lastName,email;
Button saveBtn;
FirebaseAuth auth;
FirebaseFirestore fStore;
String userID;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
firstName = findViewById(R.id.firstName);
lastName = findViewById(R.id.lastName);
email = findViewById(R.id.emailAddress);
saveBtn = findViewById(R.id.saveBtn);
auth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String First_Name= firstName.getText().toString();
String Last_Name= lastName.getText().toString();
String EMail= email.getText().toString();
if(firstName.getText().toString().isEmpty()||lastName.getText().toString().isEmpty() || email.getText().toString().isEmpty()){
Toast.makeText(Details.this, "Fill the required Details", Toast.LENGTH_SHORT).show();
return;
}
register(First_Name,Last_Name,EMail);
}
});
}
private void register(String first_name, String last_name, String eMail) {
FirebaseUser firebaseUser = auth.getCurrentUser();
assert firebaseUser != null;
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
Map<String,Object> hashmap=new HashMap<>();
hashmap.put("First Name",first_name);
hashmap.put("Last Name",last_name);
hashmap.put("Email-Id",eMail);
reference.setValue(hashmap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Intent intent=new Intent(Details.this,MainActivity.class);
startActivity(intent);
}
else{
Toast.makeText(Details.this,"Registration failed...",Toast.LENGTH_SHORT).show();
}
}
});
}
}
It seems that in your Register class in checkUserProfile() function you are checking if userId from firebaseUser.getUid() is not null. At the moment this will always be not null, because you are already asserting that the user must be authenticated at this point.
Judging from your code this is just a mistake on your part. I assume that what you are trying to do is actually see if the details already exist in the FirebaseDatabase. You have a reference to the database which you are not using.
private void checkUserProfile() {
FirebaseUser firebaseUser = auth.getCurrentUser();
assert firebaseUser != null;
String userid = firebaseUser.getUid();
//Unused reference
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
if (userid != null) {
Intent intent = new Intent(Register.this, MainActivity.class);
startActivity(intent);
}
But also my question would be, are you sure you want to use Realtime Database for user details? You are saving details in Details function using FirebaseFirestore. Didn't you want to check if the details already exist in FirebaseFirestore?
How to fix:
First, let's create the user data class:
public class User {
public String uid;
public String firstName;
public String lastName;
public String email;
public User {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public User(String uid, String firstName, String lastName, String email) {
this.uid = uid;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
}
Now, let's change the code in Details.java class to use User class:
private void register(String first_name, String last_name, String eMail) {
FirebaseUser firebaseUser = auth.getCurrentUser();
assert firebaseUser != null;
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
User user = new User(userid, firstName, lastName, eMail)
reference.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Intent intent=new Intent(Details.this,MainActivity.class);
startActivity(intent);
}
else{
Toast.makeText(Details.this,"Registration failed...",Toast.LENGTH_SHORT).show();
}
}
});
}
Let's check if the registration details exist in the database in checkUserProfile() method:
private void checkUserProfile() {
FirebaseUser firebaseUser = auth.getCurrentUser();
assert firebaseUser != null;
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Intent intent = new Intent(Register.this, MainActivity.class);
startActivity(intent);
}
else {
Toast.makeText(Register.this, "Profile doesnt exist", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Register.this, Details.class);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
Let me know if it works for you.
Firebase will generate a single unique key(UID) on registration of account whether using Email/Phone number. This key remains associated with that account until the account exists in the firebase authentication list.
So, once you register with some number/email at that time UID is created for the same. every time you fetch UID it will return that user UID, and you are also asserting Firebase User is NotNull So, every time you got UID from firebase and app move to the dashboard screen.
If you want to move users to a Detail screen then. You can also add a condition based on firebase User.
if(firebaseUser != null){
// Get UID and Move to Dashboard
}else{
// Move to Detail Screen
}

Get current user details i.e. the user which is logged in firebase

I am developing an application in which I have to get the current user details from the firebase UserNode. In my case I want to get firstname and lastname of the current user. I am successfully getting the list of all users but what to do to get the current user details who is logged in.
I use this code to get all users, please guide me what to do in this code to get the current logged in user details
DatabaseReference DataRef;
DataRef = FirebaseDatabase.getInstance().getReference().child("UserNode");
DataRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String acctname = (String)childSnapshot.child("firstname").getValue();
Log.i("name", acctname);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("error", databaseError.getMessage());
}
});
To get a particular user, you need to use in your DatabaseReference his unique identifier. So, you need to change this line:
DataRef = FirebaseDatabase.getInstance().getReference().child("UserNode");
with
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
String uid = firebaseUser.getUid();
String uid = firebaseUser.getDisplayName(); //display the entire name
DataRef = FirebaseDatabase.getInstance().getReference().child("UserNode").child(uid);
And please use this code:
DataRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String acctname = childSnapshot.child("firstname").getValue(String.class);
Log.i("name", acctname);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("error", databaseError.getMessage());
}
});
Try this Hope it helps you
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseAuth.AuthStateListener authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
String userId = firebaseUser.getUid();
String userEmail = firebaseUser.getEmail();
}
}
};

Android Firebase Set Display Name

I have been working with my app and I have set up the authentication method using email and password. I also need to set up a display name for the user which will be used in other activities such as "profile".
I have been using following method, however it does not setting the display name as I don't see it to appear in log cat. Would somebody be able to tell me where I am making mistake or should I use some other method for setting the display name.
Thanks
private void registration(){
final String email = Email.getText().toString().toString().trim();
final String password = Password.getText().toString().trim();
final String username = Username.getText().toString().trim();
final String age = Age.getText().toString().trim();
final String userID = userAuth.getCurrentUser().getUid();
if (!TextUtils.isEmpty(email)&& !TextUtils.isEmpty(password)&& !TextUtils.isEmpty(username)&& !TextUtils.isEmpty(age)){
showProgress.setMessage("Registration in progress...");
showProgress.show();
userAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
String user_id = userAuth.getCurrentUser().getUid();
DatabaseReference current_user_db = DatbaseOfUsers.child(user_id);
current_user_db.child("email").setValue(email);
current_user_db.child("username").setValue(username);
current_user_db.child("Age").setValue(age);
current_user_db.child("uID").setValue(userID);
showProgress.dismiss();
AuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null){
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(username).build();
user.updateProfile(profileUpdates);
Log.v(TAG, username);
}
}
};
//After user is created main screen intent is called
Intent mainpage = new Intent(RegisterActivity.this, MainPageActivity.class);
mainpage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainpage);
}
else if(!task.isSuccessful()){
showProgress.dismiss();
Toast.makeText(RegisterActivity.this,"Error While Register",Toast.LENGTH_LONG).show();
}
}
});
}
Take the username along with the intent
Do this way...
mainpage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent .putExtra("the key you wish to give ex:name ",username);
Then in mainpage retrieve the username by this way
String u_name;
In On create
u_name=Objects.requireNonNull(getIntent().getExtras()).getString("name");
Now u can use that username anywhere by accessing u_name

How to store data in realtime database in firebase during user registration?

I'm making socialmedia-like app that has user profile. I want to save their profile data upon their registration using their uid. Although the registration is successful, profile is not saving in the firebase database. I've also checked the rules, and read and write is set for authenticated users.
Here's my code:
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_reg;
private EditText etName, etEmail, etPassword, etCPassword, etMobile, etSchoolCompany, etLocation;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Firebase.setAndroidContext(this);
firebaseAuth = FirebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
btn_reg = (Button)findViewById(R.id.btnRegister);
etName = (EditText)findViewById(R.id.etName);
etEmail = (EditText)findViewById(R.id.etEmail);
etPassword = (EditText)findViewById(R.id.etPassword);
etCPassword = (EditText)findViewById(R.id.etCPassword);
etMobile = (EditText)findViewById(R.id.etMobile);
etSchoolCompany = (EditText)findViewById(R.id.etSchoolCompany);
etLocation = (EditText)findViewById(R.id.etLocation);
btn_reg.setOnClickListener(this);
}
#Override
public void onClick (View view){
if(view == btn_reg){
registerUser();
}
}
private void registerUser(){
String name = etName.getText().toString();
String mobile = etMobile.getText().toString();
String SchoolCompany = etSchoolCompany.getText().toString();
String location = etLocation.getText().toString();
final String email = etEmail.getText().toString().trim();
final String password = etPassword.getText().toString().trim();
String cpassword = etCPassword.getText().toString().trim();
progressDialog.setMessage("Registering..");
progressDialog.show();
//REGISTERING USER
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//THIS IS FOR STORING AUTHENTICATED USER'S DATA
final Firebase ref = new Firebase("https://myfirebase.firebaseio.com");
ref.authWithPassword(email, password, new Firebase.AuthResultHandler(){
#Override
public void onAuthenticated(AuthData authData){
// Authentication just completed successfully :)
Map<String, String> map = new HashMap<String, String>();
map.put("provider", authData.getProvider());
if(authData.getProviderData().containsKey("displayName")) {
map.put("displayName", authData.getProviderData().get("displayName").toString());
}
ref.child("users").child(authData.getUid()).setValue(map);
}
#Override
public void onAuthenticationError(FirebaseError error) {
//ERRORS TODO
}
});
progressDialog.hide();
Toast.makeText(RegisterActivity.this, "Registered Successfully", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(RegisterActivity.this, "Registration failed, please try again", Toast.LENGTH_SHORT).show();
}
}
});
}
}
From the createUserWithEmailAndPassword method reference
Tries to create a new user account with the given email address and password. If successful, it also signs the user in into the app.
That means you don't need to authenticate the user again after the signup process completed.
To make sure that the task is complete and the firebaseUser is not null, better add AuthStateListener to your FirebaseAuth instead of saving data inside onComplete method, the code is in the official guide
Then you can save the data if the user is authenticated.
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Map<String, String> map = new HashMap<>();
map.put("provider", user.getProviders().get(0));
if(user.getProviderData().containsKey("displayName")) {
map.put("displayName", user.getProviderData().get("displayName").toString());
}
ref.child("users").child(user.getUid()).setValue(map);
}
}
Suppose if you want to add the user name on database then write
String name = etName.getText().toString().trim();
then Simply create object of DatabaseReference class eg:
DatabaseReference myRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userNameRef = myRootRef.child("User Name");
userNameRef.setValue(name);
// to add email
String email = etEmail.getText().toString().trim();
DatabaseReference userEmail = myRootRef.child("Email ");
userEmail.setValue(email);
In the same way you can do it for rest of the things
This will store the data as JSON tree where the root is myRootRef and its child will be userNameRef
For anyone else having a similar problem, a common cause of data not being persisted in Firebase is the child name in Realtime Database|Rules not matching the name in your java code:
Java code:
Again, you should be calling:
ref.child("users").child(firebaseUser.getUid()).setValue(<YOUR_POJO_OBJECT>);
instead of
ref.child("users").child(authData.getUid()).setValue(map);

Categories

Resources