how to create username , address and details with firebase authentication - java

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);
}
});

Related

How to change user.getid in firebase

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.

how to check query in firestore?

Image attached for reference of firestore
trying to check the query in firestore to know if the user has sent the request or received it and it can perform the task accordingly and change the text of button.
firebaseFirestore.collection("users").document(userid).collection("request").whereEqualTo("userid",otherUserid).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()){
List<DocumentSnapshot> document = task.getResult().getDocuments();
if(document.contains("received")){
current_state="req_received";
send.setText("Accept Request");
}else if(document.contains("sent")){
current_state = "req_sent";
send.setText("Cancel Request");
}
}
}
});
The following code is to send or cancel the Request and it working fine but when I go back to another activity and come back again then the text of button changes to send request which must have stayed to cancel request as the request has already been sent.
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (userid.equals(otherUserid)) {
Toast.makeText(ProfileActivity.this, "Cannot send request to your own", Toast.LENGTH_SHORT).show();
return;
}
//--------Not friends.....
send.setEnabled(false);
if (current_state.equals("not_friends")) {
FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
// String userid = firebaseAuth.getCurrentUser().getUid();
Map<String, String> profile = new HashMap<>();
profile.put("userid", otherUserid);
firebaseFirestore.collection("users").document(userid).collection("request")
.document("sent").set(profile).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
// String userid = firebaseAuth.getCurrentUser().getUid();
Map<String, String> profile = new HashMap<>();
profile.put("userid", userid);
firebaseFirestore.collection("users").document(otherUserid).collection("request")
.document("received").set(profile).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
send.setEnabled(true);
current_state = "req_sent";
send.setText("Cancel Request");
Toast.makeText(ProfileActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
}
});
} else {
Toast.makeText(ProfileActivity.this, "Failed sending request", Toast.LENGTH_SHORT).show();
}
}
});
}
//-------- Cancel request.......
if (current_state.equals("req_sent")) {
FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
Map<String, Object> profile = new HashMap<>();
// String userid = firebaseAuth.getCurrentUser().getUid();
profile.put("userid", FieldValue.delete());
firebaseFirestore.collection("users").document(userid).collection("request")
.document("sent").update(profile).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
// String userid = firebaseAuth.getCurrentUser().getUid();
Map<String, Object> profile = new HashMap<>();
profile.put("userid", FieldValue.delete());
firebaseFirestore.collection("users").document(otherUserid).collection("request")
.document("received").update(profile).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
send.setEnabled(true);
current_state = "not_friends";
send.setText("Send Request");
Toast.makeText(ProfileActivity.this, "Request canceled", Toast.LENGTH_SHORT).show();
}
}
});
} else {
Toast.makeText(ProfileActivity.this, "Failed request canceled", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
}
As you confirmed, if the error lies only on the comparison part changing the query iteration like below might fix the issue.
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
if(document.getId().contains("received")){
current_state="req_received";
send.setText("Accept Request");
// do pending stuffs or break the loop here
} else if(document.getId().contains("sent")){
current_state = "req_sent";
send.setText("Cancel Request");
// do pending stuffs or break the loop here
}
}
}
ref: https://firebase.google.com/docs/firestore/query-data/queries

Re-authenticate a user with GoogleAuthProvider doesn't work

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();
}

How to register user into firebase registration?

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);
}

How to save data to same table from different activities?

Below is the code for both of my activities. By coding like this, the data get stored like this in firebase. This is a snapshot of the stored data:
This is what I get:
What I want is this
I know that this happens because I have two class for the database but I have tried to put in one class but it didn't work. I think it is because of my codes
Below are my codes:
Registration ACtivity`public class RegisterActivityUser extends AppCompatActivity {
ImageView ImgUserPhoto;
static int PReqCode=1;
static int REQUESTCODE=1;
Uri pickedImgUri;
//*************** Firebase User Auth **********//
private EditText userEmail, userPassword, userPassword2, userName, userWeight, userHeight;
private ProgressBar loadingProgress;
private Button regBtn;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_user);
//*************** Login Account User *************//
//Ini Views
userEmail=findViewById(R.id.redMail);
userPassword=findViewById(R.id.regPassword);
userPassword2=findViewById(R.id.regPassword2);
userName=findViewById(R.id.regName);
loadingProgress=findViewById(R.id.progressBar);
regBtn = findViewById(R.id.regBtn);
loadingProgress.setVisibility(View.INVISIBLE);
userWeight=findViewById(R.id.userWeight);
userHeight=findViewById(R.id.userHeight);
mAuth= FirebaseAuth.getInstance();
regBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
regBtn.setVisibility(View.INVISIBLE);
loadingProgress.setVisibility(View.VISIBLE);
final String email=userEmail.getText().toString().trim();
final String password=userPassword.getText().toString();
final String password2=userPassword2.getText().toString();
final String name=userName.getText().toString().trim();
if (email.isEmpty() || name.isEmpty() || password.isEmpty() || password2.isEmpty() || !password.equals(password2)){
//something goes wrong, all fields must be filled
//we need to display error message
showMessage("Please Fill All Details Above");
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
else {
//everything is okay
//Create New User Account
CreateUserAccount(email,name,password);
}
}
}) ;
ImgUserPhoto = findViewById(R.id.editUserPhoto) ;
ImgUserPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT>=23){
checkAndRequestForPermission();
}
else {
openGallery();
}
}
});
}
// ************* Create User Account *************//
private void CreateUserAccount(final String email, final String name, String password) {
//this method to create user account with specific email and password;
mAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
//user account created successfully
User user = new User(
name,
email
);
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
//progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
//acc successfully registered
showMessage("Account Created");
//after we created account, we need to update the user profile picture
updateUserInfo (name ,pickedImgUri,mAuth.getCurrentUser());
}
else{
showMessage("User Already Have Account" + task.getException().getMessage());
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
}
});
}
else {
// user account failed
}
}
});
}
// ************* update user name and photo ************* //
private void updateUserInfo(final String name, Uri pickedImgUri, final FirebaseUser currentUser) {
StorageReference mStorage = FirebaseStorage.getInstance().getReference().child("users_photos");
final StorageReference imageFilePath = mStorage.child(pickedImgUri.getLastPathSegment());
imageFilePath.putFile(pickedImgUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//image Uploaded Successfully
//now we can get our image URL
imageFilePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//uri contain user image URL
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setDisplayName(name)
.setPhotoUri(uri)
.build();
currentUser.updateProfile(profileUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
// User Profile has updated successfully
showMessage("Register Complete");
updateUI();
}
}
});
}
});
}
});
}
private void updateUI() {
Intent editProfileActivity = new Intent(RegisterActivityUser.this,EditProfileActivity.class);
startActivity(editProfileActivity);
finish();
}
// ************* simple method to toast message *************//
private void showMessage(String message) {
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}
// ************* Upload Picture *************//
private void openGallery() {
//TODO: open gallery intent and wait user to pick an image!
Intent galleryIntent=new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,REQUESTCODE);
}
private void checkAndRequestForPermission() {
if (ContextCompat.checkSelfPermission(RegisterActivityUser.this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(RegisterActivityUser.this,Manifest.permission.READ_EXTERNAL_STORAGE)){
Toast.makeText(RegisterActivityUser.this, "Please accept for required Permission",Toast.LENGTH_SHORT).show();
}
else
{
ActivityCompat.requestPermissions(RegisterActivityUser.this,
new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},
PReqCode);
}
}
else
{
openGallery();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode==RESULT_OK && requestCode == REQUESTCODE && data !=null){
//the user has success picked an image
//we need to save its as reference to a Uri Variable
pickedImgUri=data.getData();
ImgUserPhoto.setImageURI(pickedImgUri);
}
}
}
`
This one edit profile activity: `private void updateUserInfo(final String weight, final String height, final FirebaseUser currentUser) {
/*Glide.with(this).load(currentUser.getPhotoUrl()).into(userImage);*/
mAuth.updateCurrentUser(currentUser).addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.build();
currentUser.updateProfile(profileUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
UserProfile user = new UserProfile (
weight,
height
);
FirebaseDatabase.getInstance().getReference("Users Profile")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
//progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
//acc successfully registered
showMessage("Account Updated");}
else{
}
}
});
}
}
});
Replace this:
UserProfile user = new UserProfile (
weight,
height
);
FirebaseDatabase.getInstance().getReference("Users Profile")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user)
With:
Map<String, Object> values = new HashMap<>();
values.put("height", height);
values.put("weight", weight);
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.updateChildren(values)
The relevant changes:
Call updateChildren instead of setValue, since setValue replace all data at the location you call it on.
Get a reference to /Users instead of /Users Profile.
Additional hint: consider storing the height and weight as numeric values, instead of strings. Otherwise ordering/filtering on them will become confusing, as Firebase uses lexicographical ordering for strings.

Categories