I'm trying to store details of user like name, email,age etc using Firebase in Android Studio, but it seems only the email and pasword is getting stored. Here's my code, where have I done mistakes? Only the real time database part of Firebase isn't somehow working here. Also, I couldn't post full code here because of "most of it is code add some more details" error.
regButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Email,Password etc are variables
final String Email= email.getText().toString().trim();
final String Password= password.getText().toString().trim();
final String FullName= fullName.getText().toString().trim();
final String Phone= phone.getText().toString().trim();
final String Gender= gender.getText().toString().trim();
final String Age= age.getText().toString().trim();
if (TextUtils.isEmpty(Email)){
email.setError("Email is required!");
return;
}
else{
loader.setMessage("Registration in process....");
loader.setCanceledOnTouchOutside(false);
loader.show();
mAuth.createUserWithEmailAndPassword(Email,Password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
String error =task.getException().toString();
Toast.makeText(SelectRegistrationActivity.this,
"Error occurred:" + error,Toast.LENGTH_SHORT).show();
}
else{
String currentUserId = mAuth.getCurrentUser().getUid();
userDatabaseRef= FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserId);
HashMap userInfo=new HashMap();
userInfo.put("Name",fullName);
userInfo.put("Email",email);
userInfo.put("Age",age);
userInfo.put("Gender",gender);
userInfo.put("Phone",phone);
userInfo.put("Type","Patient");
userDatabaseRef.updateChildren(userInfo).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()){
Toast.makeText(SelectRegistrationActivity.this, "Details set Successful", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(SelectRegistrationActivity.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
finish();
loader.dismiss();
}
});
}
}
});
Related
public void register(final String username, final String fullname, String email, String password) {
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
pd.show();
FirebaseUser firebaseUser = auth.getCurrentUser();
String userID ="Queenlab#"+firebaseUser.getUid();
// circleIV.setImageDrawable(drawable2);
reference = FirebaseDatabase.getInstance().getReference().child("Users").child(userID);
HashMap<String, Object> map = new HashMap<>();
map.put("id",userID);
map.put("username", username.toLowerCase());
map.put("fullname", fullname);
map.put("imageurl", "https://th.bing.com/th/id/OIP.PXxWJplK9ObsWdxdFCqLOwHaE8?pid=ImgDet&rs=1");
map.put("bio", "");
map.put("instgram", "");
reference.setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(RegisterActivity.this, "Register sccessful sending Email Verification", Toast.LENGTH_SHORT).show();
sendVerificationEmail();
auth.signOut();
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
});
} else {
pd.dismiss();
Toast.makeText(RegisterActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
The UID of a user is determined by the authentication provider. It can't be set from client-side application code, as that would be a security risk.
If you want to determine the UID of your users, you can implement your own provider. Note that this will include writing code that runs in a trusted environment, such as a server that you control, or Cloud Functions/Cloud Run.
Alternatively you can implement a mapping from the UID of the user to whatever ID system you want to use in your database.
I have a setup system to send name, email, profile pic, biography and username.
Then I did check if the username is taken into Firebase Firestore by QuerySnapshot (working) my problem is that when I change to an available username, the app enters into a loading loop and do nothing more. It doesn't send to the database or anything else.
I tried many times to solve this problem, but didn't find any solution yet. I moved the code, reorganized and nothing seens to solve.
The method is inside the onClick from a button.
Here's the code:
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setup_progressbar.setVisibility(View.VISIBLE);
String name = setup_name.getText().toString();
String username = setup_username.getText().toString();
String userbio = setup_bio.getText().toString();
String email = setup_email.getText().toString();
if (!TextUtils.isEmpty(name) && mainImageURI != null) {
Query mQuery = db.collection("Users")
.whereEqualTo("username", username);
mQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
for (DocumentSnapshot document: documentSnapshots){
if (document!=null){
duplicate = document.getString("username");
setup_username.setError("Ouch! This username is already taken. Please, try another.");
setup_progressbar.setVisibility(View.INVISIBLE);
} else {
if (isChanged) {
setup_progressbar.setVisibility(View.VISIBLE);
userid = firebaseAuth.getCurrentUser().getUid();
StorageReference imagePath = storageReference.child("profile_images").child(userid + ".jpg");
//StorageReference coverPath = storageReference.child("cover_images").child(userid + ".jpg");
imagePath.putFile(mainImageURI).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
imagePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
storeFireStore(uri, name, username, userbio, email);
FancyToast.makeText(getApplicationContext(), getString(R.string.enviando_foto), FancyToast.LENGTH_LONG, FancyToast.CONFUSING, R.drawable.ic_upload, false).show();
setup_progressbar.setVisibility(View.INVISIBLE);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
String error = e.getMessage().toString();
FancyToast.makeText(getApplicationContext(), getString(R.string.fail_to_update_profile_pic) + error, FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show();
setup_progressbar.setVisibility(View.INVISIBLE);
}
});
}
});
} else {
storeFireStore(null, name, username, userbio, email);
}
}
}
}
});
} else {
if (TextUtils.isEmpty(name)) {
setup_progressbar.setVisibility(View.INVISIBLE);
Snackbar snackbar = Snackbar.make(frameLayout, getString(R.string.empty_name), Snackbar.LENGTH_LONG);
snackbar.show();
} else if (TextUtils.isEmpty(username)) {
setup_progressbar.setVisibility(View.INVISIBLE);
Snackbar snackbar = Snackbar.make(frameLayout, getString(R.string.empty_username), Snackbar.LENGTH_LONG);
snackbar.show();
} else if (TextUtils.equals(username, duplicate)){
setup_username.setError("Ouch! This username is already taken. Please, try another.");
setup_progressbar.setVisibility(View.INVISIBLE);
} else if (TextUtils.isEmpty(email)) {
setup_progressbar.setVisibility(View.INVISIBLE);
Snackbar snackbar = Snackbar.make(frameLayout, getString(R.string.email_confirm), Snackbar.LENGTH_LONG);
snackbar.show();
} else {
setup_progressbar.setVisibility(View.INVISIBLE);
Snackbar snackbar = Snackbar.make(frameLayout, getString(R.string.pick_a_profile_pic), Snackbar.LENGTH_LONG);
snackbar.show();
}
}
}
private void storeFireStore(Uri uri, String name, String username, String userbio, String email) {
if (uri != null) {
downloadUrl = uri;
} else {
downloadUrl = mainImageURI;
//downloadUrl = mainCoverURI;
}
Map<String, String> userMap = new HashMap<>();
userMap.put("name", name);
userMap.put("username", username);
userMap.put("userbio", userbio);
userMap.put("email", email);
userMap.put("image", downloadUrl.toString());
//userMap.put("cover",downloadUrl.toString());
firebaseFirestore.collection("Users").document(userid).set(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
FancyToast.makeText(getApplicationContext(), getString(R.string.profileUpdated), FancyToast.LENGTH_LONG, FancyToast.SUCCESS, false).show();
setup_progressbar.setVisibility(View.INVISIBLE);
finish();
} else {
String error = task.getException().getMessage();
FancyToast.makeText(getApplicationContext(), getString(R.string.fail_to_update_profile) + error, FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show();
}
}
});
}
});
Here's a screenshot of the screen loop.
You likely don't need (or want) a "snapshot listener" for this use case. You likely just want to do a one-time fetch to see if the given user name exists.
You likely want to use a TRANSACTION in Firestore to first read if a matching document exists and if not to transaction.set() a new document. That way if others come in at the same time trying to create a doc with the same username, only one of the competing concurrent transactions will succeed.
Consider inserting the document to Firestore before you upload the item to Storage. It is the document is Firestore that is the potential "race-condition". Once you "own" the FS document, you can take your time to upload/update other data.
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.
I try to upload my profile picture, also I get the message of the profile picture is been successfully upload but not able to see it in setting activity
I tried to change the firebase account but not able to work.
when I select photo it takes me to my internal storage, when I select the image it again takes me to choose section of photo uploading ways such as album, google photos internal storage, download etc. when the photo is been uploaded it is been showing in the firebase storage section but it is not showing in the app.
here is the code link
RootRef.child("Users").child(currentUserID)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("image")))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveUserStatus = dataSnapshot.child("status").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrieveUserStatus);
Picasso.get().load(retrieveProfileImage).into(userProfileImage);
}
else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name"))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveUserStatus = dataSnapshot.child("status").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrieveUserStatus);
}
else {
userName.setVisibility(View.VISIBLE);
Toast.makeText(SettingsActivity.this, "Check The Details Again.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void UpdateSettings() {
String setUserName = userName.getText().toString();
String setStatus = userStatus.getText().toString();
if (TextUtils.isEmpty(setUserName)) {
Toast.makeText(this, "UserName is Empty.", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(setStatus)) {
Toast.makeText(this, "Status is Empty.", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, String> profileMap = new HashMap<>();
profileMap.put("uid", currentUserID);
profileMap.put("name", setUserName);
profileMap.put("status", setStatus);
RootRef.child("Users").child(currentUserID).setValue(profileMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
SendUserToMainActivity();
Toast.makeText(SettingsActivity.this, "Profile Updates. Thank You!!!", Toast.LENGTH_SHORT).show();
}
else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
}```
I think you missed to send image from your app.
In UpdateSettings() method you have to send image to firebase.
In below HashMap add image and send to firebase,
HashMap<String, String> profileMap = new HashMap<>();
profileMap.put("uid", currentUserID);
profileMap.put("name", setUserName);
profileMap.put("status", setStatus);
profileMap.put("image", [YOUR_IMAGE_STRING]);
I am going to insert my email and password into Firebase Authentication. However, the code that I found on the Internet does not work for me? Below is the code and when I click next button, it goes back to the previous page too, it does not proceed with the next page?
public void completeRegis() {
username1 = username.getText().toString().trim();
email1 = email.getText().toString().trim();
psd1 = psd.getText().toString().trim();
psd2 = reconpsd.getText().toString().trim();
mAuth.createUserWithEmailAndPassword(email1, psd1)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//start profile activity here
User user = new User(username1, email1,psd1);
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(RoleInfo1.this, "Registration successful.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(RoleInfo1.this, HomePage.class ));
progressBar.setVisibility(View.GONE);
} else {
Toast.makeText(RoleInfo1.this, "Database not created", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
} else {
Toast.makeText(RoleInfo1.this, "Registration not successful, please try again.", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
}
private void initializeUI() {
username = findViewById(R.id.usernameregister);
email = findViewById(R.id.emailregister);
psd = findViewById(R.id.psdregister);
reconpsd = findViewById(R.id.reconpsdregister);
progressBar = findViewById(R.id.progressBar);
}
}
I am very new to android but I recently made a signUp page successfully.
declare a firebase auth instance
private FirebaseAuth mAuth;
private EditText mName, mEmailField, mConfirmPass, mNewPass;
then in onCreate() I declared them as
mName = (EditText) findViewById(R.id.eName);
mEmailField = (EditText) findViewById(R.id.fieldEmail);
mConfirmPass = (EditText) findViewById(R.id.fieldConfirm);
mNewPass = (EditText) findViewById(R.id.fieldNew);
mAuth = FirebaseAuth.getInstance();
I added a button in the authentication page for signup. Clicking on it starts the signUp procedure. This is done in onCreate() method
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startSignUp();
}
});
Then I declare the startSignUp() method as below
public void startSignUp(){
String name = mName.getText().toString();
String email = mEmailField.getText().toString();
String newPass = mNewPass.getText().toString();
String conPass = mConfirmPass.getText().toString();
if(TextUtils.isEmpty(name) || TextUtils.isEmpty(email) || TextUtils.isEmpty(newPass) || TextUtils.isEmpty(conPass)){
Toast.makeText(SignUp.this, "Fields Empty" , Toast.LENGTH_LONG).show();
}
mAuth.createUserWithEmailAndPassword(email,newPass).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(! task.isSuccessful()){
Toast.makeText(SignUp.this, "SignUp Failed", Toast.LENGTH_LONG).show();
}else {
openAuthetication();
}
}
});
}
}
If signUp is successful, it will go back to the authentication page for signing in. This is done in the openAuthetication() method.
public void openAuthetication(){
Intent intent = new Intent(this, Authetication.class);
startActivity(intent);
}