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
Related
I have a problem, I can't register in my chat app. It shows me that "You can't register". I don't know where is the problem. I set read and write to true in my database but it still not working. I use the last versions of Firebase. I haven't problems with the internet and connected firebase to my project successfully.
This is my register activity
MaterialEditText username, email, password;
Button btn_register;
FirebaseAuth auth;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Регистрация");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
username = findViewById(R.id.username);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
btn_register = findViewById(R.id.btn_register);
auth = FirebaseAuth.getInstance();
btn_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt_username = username.getText().toString();
String txt_email = email.getText().toString();
String txt_password = password.getText().toString();
if (TextUtils.isEmpty(txt_username) || TextUtils.isEmpty(txt_email) || TextUtils.isEmpty(txt_password)) {
Toast.makeText(RegisterActivity.this, "Write more", Toast.LENGTH_SHORT).show();
} else if (txt_password.length() < 6 ){
Toast.makeText(RegisterActivity.this, "Password too short ", Toast.LENGTH_SHORT).show();
} else {
register(txt_username, txt_email, txt_password);
}
}
});
}
private void register(final String username, String email, String password){
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, 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");
reference.setValue(HashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
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, "You cant register", Toast.LENGTH_SHORT).show();
}
}
});
}
}
When initializing your FirebaseDatabase reference, the item node with the provided user id does not exist yet in your database thus the reference is null
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
Instead, initialize the reference to the Users node
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users");
Then when saving the user's data you can save to their userId:
reference.child(userid).setValue(HashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
...
});
in manifest file allow internet permission. if you continue this err create failure listener and print failure code
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
Everything worked but not showing name only.
My code is:
user = profAuth.getCurrentUser();
if (user != null) {
// Name, email address
String uid = user.getUid();
String name = user.getDisplayName();
String email = user.getEmail();
txtName.setText(name);
txtEmail.setText(email);
txtUserid.setText(uid);
}
That's because Firebase Auth doesn't prompt the user to provide a Display name when signing up with Email/Password. But you can do that manually. Prompt the user to type the display name he desires, and pass it to the setDisplayName() method bellow:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(desiredName)
.build();
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User display name updated.");
}
}
});
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.
FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseAuth mAuth;
EditText name, email, password;
Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d("########", "onAuthStateChanged:signed_in:" + user.getUid());
}
else{
// User is signed out
Log.d("########", "onAuthStateChanged:signed_out");
}
}
};
name = (EditText) findViewById(R.id.input_name);
email = (EditText) findViewById(R.id.input_email);
password = (EditText) findViewById(R.id.input_password);
submit = (Button) findViewById(R.id.btn_signup);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.createUserWithEmailAndPassword(email.getText().toString(), password.getText().toString()).addOnCompleteListener(SignUp.this, new OnCompleteListener < AuthResult > () {
#Override
public void onComplete(#NonNull Task < AuthResult > task) {
Log.d("###########", "signInWithEmail:onComplete:" + task.isSuccessful());
}
});
The Task.isSuccessful() always returns false and I am not able to add any user.
I have enabled email authentication on Firebase and am able to add users from the forge itself, i am left with no way to debug and figure out where the issue is.
All other settings like adding dependencies and copying the configuration file obtained from Firebase into the app directory have been done. Please help.
I encountered the same problem, and decided to create a user from the firebase console. Then the error displayed in the image came up. The password is required to be at least 6 characters long. When signing up a new user ensure that the length of password is at least six and it should work.
I attached addOnFailureListener() and it abused:
The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.
private void register(final String user, String email,final String password) {
auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
FirebaseUser firebaseUserLcl = auth.getCurrentUser();
String userIdLcl = firebaseUserLcl.getUid();
l.a("userIdLcl="+userIdLcl);
DatabaseReference referenceLcl = FirebaseDatabase.getInstance().getReference("Users").child(userIdLcl);
HashMap<String, String> mapLcl = new HashMap();
mapLcl.put("id", userIdLcl);
mapLcl.put("email", email);
mapLcl.put("password", password);
mapLcl.put("ImageURL", "default");
referenceLcl.setValue(mapLcl).addOnCompleteListener(taskPrm -> {
if (taskPrm.isSuccessful()) {
Intent intentLcl = new Intent(RegisterActivity.this, MainActivity.class);
intentLcl.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intentLcl);
finish();
}else {
Toast.makeText(RegisterActivity.this, "Signing failed,", Toast.LENGTH_LONG).show();
}
});
} else {
// l.a(task.getException().getCause());
Toast.makeText(RegisterActivity.this, "You cannot register with this email or password", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener( e->
l.a(e.getMessage()) //logging
);
}
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);