The way data is being saved in Firebase is that the User ID is under each Push ID, whereas it should have been the other way around; that is Push ID under User ID.
What do I have to change in my code?
private void saveServiceDetails(){
adService1 adService1 = new adService1(Name, Description, Category, downloadUrl, lat, lng);
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Saving information..., please wait");
progressDialog.show();
FirebaseUser user = firebaseAuth.getCurrentUser();
databaseReference.child(user.getUid()).setValue(adService1)
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Information saved...", Toast.LENGTH_LONG).show();
}
}
});
}
Try this code :
....
FirebaseUser user = firebaseAuth.getCurrentUser();
String key = databaseReference.child(user.getUid()).push().getKey();
databaseReference.child(user.getUid()).child(key).setValue(adService1)
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Information saved...", Toast.LENGTH_LONG).show();
}
}
});
Related
I used firebase phone and google authentication in my app I am facing an issue that when a user logout and signing again though OTP or google it signup the user again by creating new user id and all the information that user update through profile update option erased and come back in original state as new user and all updates of profile lost.
My phone sign in code is here
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber(phoneNumber)
.setTimeout(120L, TimeUnit.SECONDS)
.setActivity(this)
.setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
}
#Override
public void onCodeSent(#NonNull String verifyId, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(verifyId, forceResendingToken);
verificationId = verifyId;
}
}).build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
public void callNextScreen(View view) {
dialog.show();
String otp = binding.otpView.getText().toString();
if (otp!= null) {
verifyOTP(otp);
} else {
Toast.makeText(this, "Enter code", Toast.LENGTH_LONG).show();
}
}
private void verifyOTP(String otp) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, otp);
auth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
String uid = auth.getCurrentUser().getUid();
String phoneNumber = auth.getCurrentUser().getPhoneNumber();
User users = new User();
users.setPhone(phoneNumber);
database
.collection("users")
.document(uid)
.set(users).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
dialog.dismiss();
Intent intent = new Intent(OTP_Activity.this, MainActivity.class);
startActivity(intent);
finishAffinity();
} else {
dialog.dismiss();
Toast.makeText(OTP_Activity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
} else {
dialog.dismiss();
Toast.makeText(OTP_Activity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
and my user attributes and user class constructor looks like this
private String name, email, image, phone, gender;
private long coins = 500;
public User(String name, String email, String image, String phone, String gender) {
this.name = name;
this.email = email;
this.image = image;
this.phone = phone;
this.gender = gender;
}
public User() {
}
this is how creating user profile with google signing
private void firebaseAuthWithGoogle(String idToken){
AuthCredential firebaseCredential = GoogleAuthProvider.getCredential(idToken, null);
auth.signInWithCredential(firebaseCredential)
.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
Log.d("TAG", "signInWithCredential:success");
FirebaseUser user = auth.getCurrentUser();
String uid = user.getUid();
User newUser = new User();
newUser.setName(user.getDisplayName());
newUser.setEmail(user.getEmail());
newUser.setImage(user.getPhotoUrl().toString());
database
.collection("users")
.document(uid)
.set(newUser).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
dialog.dismiss();
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
startActivity(intent);
finishAffinity();
} else {
dialog.dismiss();
Log.w("TAG", "signInWithCredential:failure", task.getException());
Toast.makeText(SignupActivity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
} else {
dialog.dismiss();
// If sign in fails, display a message to the user.
Toast.makeText(SignupActivity.this, "Signup Failed", Toast.LENGTH_SHORT).show();
// updateUI(null);
}
}
});
}
progress dialog does not dismiss and because of no response from firebase real-time database
I add also authentication another page its works, but save information in realtime won't work, I create a firebase real-time bucket also
this is a simple test but no response progress is running.
btnLogIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt_email=email.getText().toString();
String txt_password=password.getText().toString();
final ProgressDialog progressDialog =new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("Loging in");
progressDialog.show();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("User");
reference.push().setValue("hi").addOnCompleteListener(new OnCompleteListener<Void () {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(LoginActivity.this, "success", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(LoginActivity.this, "no success "+ task.getException().getMessage()
, Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, "fail : "+e.getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
});
this is my rules of realtime data base
this is my real time data base
This is actually my firebase integration works or not
and registration code is below. authentication works but real-time not works. don't store data and don't give me any type of message. and progress dialog is running not dismiss because of real-time not response.
private void register(final String username, final String email, String password, final String phone){
auth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
FirebaseUser firebaseUser=auth.getCurrentUser();
assert firebaseUser!=null;
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
HashMap<String ,String> hashMap= new HashMap<>();
hashMap.put("id", userid);
hashMap.put("username", username);
hashMap.put("imageUrl","default");
hashMap.put("email",email);
hashMap.put("phone",phone);
Toast.makeText(RegisterActivity.this, "sign in but not insert", Toast.LENGTH_SHORT).show();
reference.setValue(hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
/* SharedPreferences preferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(STATUS,"student");
editor.apply();*/
Toast.makeText(RegisterActivity.this, "finish set up", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
Intent intent= new Intent(RegisterActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}else {
Toast.makeText(RegisterActivity.this, "failed to add database", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
}else{
Toast.makeText(RegisterActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
}
please help me how can I fix the real-time database?
Firebase register code is given below. When I add username as a parameter, the method does not let me do it.
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//checking if success
if(task.isSuccessful()){
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}else{
//display some message here
Toast.makeText(RegisterActivity.this,"Bir hata oldu",Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
you need to update user after creating it.
firebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(YourActivity.this, "An error occurred", Toast.LENGTH_SHORT).show();
} else {
addUserNameToUser(task.getResult().getUser());
}
}
)};
private void addUserNameToUser(User user){
String username = "username";
String email = user.getEmail();
String userId = user.getUid();
User user = new User(username, email);
firebaseDB.child("users").child(userId).setValue(user);
}
the variable firebaseDB should be created before. You can create in where you create firebaseAuth like so ;
firebaseDB = FirebaseDatabase.getInstance().getReference();
Update 1
using com.google.firebase:firebase-auth:11.6.2
public class MainActivity extends AppCompatActivity {
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.createUserWithEmailAndPassword("erginersoyy#gmail.com", "12345").addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(MainActivity.this, "An error occurred", Toast.LENGTH_SHORT).show();
} else {
addUserNameToUser(task.getResult().getUser());
}
}
});
}
private void addUserNameToUser(FirebaseUser user) {
String username = "username";
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(username)
.setPhotoUri(Uri.parse("https://example.com/jane-q-user/profile.jpg"))
.build();
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User profile updated.");
}
}
});
}
}
you can also check this link
I have created the Register method using firebase authentication user register method.
How to delete a registered user by using firebase auth and android studio?
private void registerUser(){
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
firebaseAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>(){
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//user successfully registered and logged in
Toast.makeText(MainActivity.this, "Registered Successfully",Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
finish();
startActivity(new Intent(getApplicationContext(),ProfileActivity.class));
}else{
Toast.makeText(MainActivity.this, "Could Not Register. Please Try Again Later",Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
}
private void deleteUser(){
// TODO: Fill this method
}
You can use delete() method to remove the desired user from the Firebase. Please use this code:
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
AuthCredential authCredential = EmailAuthProvider.getCredential("user#example.com", "password1234");
firebaseUser.reauthenticate(authCredential).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
firebaseUser.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User account deleted!");
}
}
});
}
});
It seems I can only find a way to update the display name of a current user, although I would like to do it while registering.
Here is the code I have been trying but it is not working, i have read about a bug in firebase that requires signing out for the display name to show but this hasnt solved my problem. Here is the code
public void btnRegistrationUser_Click(View v) {
final String email = txtEmailAddress.getText().toString();
final String password = txtPassword.getText().toString();
final String username = txtUsername.getText().toString();
final ProgressDialog progressDialog = ProgressDialog.show(RegistrationActivity.this, "Please wait...", "Processing...", true);
(firebaseAuth.createUserWithEmailAndPassword(email,password ))
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (task.isSuccessful()) {
//Sign in the user here
signin(email,password,username);
}
else
{
Log.e("ERROR", task.getException().toString());
Toast.makeText(RegistrationActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
private void signin(String email, String password, final String username) {
firebaseAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//New Account is signed in and now the Current User
FirebaseUser user = firebaseAuth.getInstance().getCurrentUser();
Toast.makeText(RegistrationActivity.this, "curr user is "+user.getEmail(), Toast.LENGTH_LONG).show();
Toast.makeText(RegistrationActivity.this, "passed in username is "+username, Toast.LENGTH_LONG).show();
firebaseAuth.getInstance().signOut();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(username)
.build();
// Toast.makeText(RegistrationActivity.this, "Registration successful", Toast.LENGTH_LONG).show();
Toast.makeText(RegistrationActivity.this, "curr display name is "+user.getDisplayName(), Toast.LENGTH_LONG).show();
Intent i = new Intent(RegistrationActivity.this, LoginActivity.class);
startActivity(i);
}
}
});
}
}
Thanks
Maybe you could try to login the user since the account registration is successful. That way the current user would be the currently registered one.
public void btnRegistrationUser_Click(View v) {
final String email = txtEmailAddress.getText().toString();
final String password = txtPassword.getText().toString();
final String username = txtUsername.getText().toString();
final ProgressDialog progressDialog = ProgressDialog.show(RegistrationActivity.this, "Please wait...", "Processing...", true);
(firebaseAuth.createUserWithEmailAndPassword(email,password ))
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (task.isSuccessful()) {
//Sign in the user here
signin(email,password,username);
}
else
{
Log.e("ERROR", task.getException().toString());
Toast.makeText(RegistrationActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
private void signin(String email, String password, final String username) {
firebaseAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//New Account is signed in and now the Current User
FirebaseUser user = firebaseAuth.getInstance().getCurrentUser();
Toast.makeText(RegistrationActivity.this, "curr user is "+user.getEmail(), Toast.LENGTH_LONG).show();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(username)
.build();
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(RegistrationActivity.this, "curr display name is "+user.getDisplayName(), Toast.LENGTH_LONG).show();
}
}
});
Intent i = new Intent(RegistrationActivity.this, LoginActivity.class);
startActivity(i);
}
}
});
You also forgot the user by calling the updateProfile() method.
Check this out for more info: https://firebase.google.com/docs/auth/android/manage-users