query with the realtime firebase in android studio - java

first i'm sorry of my bad english , i have a problem with my code , when i want to query and check if the user that sign in is in the database or not , and also check of his password and if he tourist or tour guide and when i debug the program , the first statement is passed and the second which is check of the password , he never passed and start the next page , it say that the password is wrong , how i fix this problem pleass :(
TextView show7, signup_btn_label;
ImageButton imagebuttonn1;
EditText tourg_email_address, tourg_password;
Button btnn_login;
private FirebaseAuth mAuth1;
private DatabaseReference jLoginDatabase;
private FirebaseDatabase fDatabase;
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logintourguide);
//initialise mProgressDialog
mProgressDialog = new ProgressDialog(Logintourguide.this);
show7 = (TextView) findViewById(R.id.forgot_password);
show7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Forgetpassword.class);
startActivity(i);
}
});
imagebuttonn1 = findViewById(R.id.imagebuttonn);
imagebuttonn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
signup_btn_label = (TextView) findViewById(R.id.signup_btn_label);
signup_btn_label.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), activity_signup_tourguide.class);
startActivity(i);
}
});
tourg_email_address = (EditText) findViewById(R.id.tourg_email_address);
tourg_password = (EditText) findViewById(R.id.tourg_password);
btnn_login = (Button) findViewById(R.id.btnn_login);
mAuth1 = FirebaseAuth.getInstance();
btnn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
final String email = tourg_email_address.getText().toString().trim();
final String pass = tourg_password.getText().toString().trim();
if (TextUtils.isEmpty(email)) {
Toast.makeText(Logintourguide.this, "Please enter your email", Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(pass)) {
Toast.makeText(Logintourguide.this, "Please enter your password", Toast.LENGTH_LONG).show();
return;
}
if (tourg_password.length() < 8) {
Toast.makeText(Logintourguide.this, "password must be 8 or long", Toast.LENGTH_LONG).show();
return;
}
if (!email.matches(emailPattern)) {
Toast.makeText(Logintourguide.this, "invalid email address", Toast.LENGTH_LONG).show();
return;
}
//show dialog
mProgressDialog.show();
//set content view
mProgressDialog.setContentView(R.layout.progress_dialog);
//set transparent background
mProgressDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
///FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
final String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
// DatabaseReference rootRef = FirebaseDatabase.getInstance()
final DatabaseReference uidRef = FirebaseDatabase.getInstance().getReference("Users");
final Query checkUser = uidRef.orderByChild("email").equalTo(email);
checkUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (pass.equals(dataSnapshot.child("password").getValue())) {
if (dataSnapshot.child("sign up as").getValue().equals("Tour Guide")) {
String passwordfromDB = (String) dataSnapshot.child("password").getValue(String.class);
String emailfromDB = (String) dataSnapshot.child("email").getValue(String.class);
String fullNamefromDB = (String) dataSnapshot.child("fullName").getValue(String.class);
String phoneNumberfromDB = (String) dataSnapshot.child("phoneNumber").getValue(String.class);
//put it iin that intent so we can pass it to tourguide class
Intent intent = new Intent(getApplicationContext(), TourGuide_Profile.class);
intent.putExtra("full name", fullNamefromDB);
intent.putExtra("email", emailfromDB);
intent.putExtra("phone No", phoneNumberfromDB);
intent.putExtra("password", passwordfromDB);
mProgressDialog.dismiss();
Toast.makeText(Logintourguide.this, "welcome back tour guide!",
Toast.LENGTH_SHORT).show();
startActivity(intent);
} else {
mProgressDialog.dismiss();
Toast.makeText(Logintourguide.this, "Sorry ! You are not authorized to access this application!",
Toast.LENGTH_SHORT).show();
}
} else {
mProgressDialog.dismiss();
Toast.makeText(Logintourguide.this, "wrong password",
Toast.LENGTH_SHORT).show();
}
} else {
mProgressDialog.dismiss();
Toast.makeText(Logintourguide.this, "no such user exist !",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("Tag", databaseError.getMessage());
}
});
// uidRef.addListenerForSingleValueEvent(valueEventListener);
// checkUser.addListenerForSingleValueEvent(valueEventListener);
}
});
}

Related

How to add auto uid field in Firebase Firestore

I want to add an auto uid field in the firebase firestore when a user register their account. How to implement that in my codes to add uid which is generated by the firebase?
Here is my register.java codes:
public class Register extends AppCompatActivity {
//Variables
TextInputLayout username, email, PhoneNo, password;
RadioGroup radioGroup;
RadioButton selectedElderly, selectedGuardian;
Button regBtn, regToLoginBtn;
FirebaseAuth fAuth;
FirebaseFirestore fStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
//Hooks to all xml elements in activity_register.xml
username = findViewById(R.id.reg_username);
email = findViewById(R.id.reg_email);
PhoneNo = findViewById(R.id.reg_phoneNo);
password = findViewById(R.id.reg_password);
regBtn = findViewById(R.id.reg_btn);
regToLoginBtn = findViewById(R.id.reg_login_btn);
radioGroup = findViewById(R.id.radio_type);
selectedGuardian = findViewById(R.id.radioGuardian);
selectedElderly = findViewById(R.id.radioElderly);
regToLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Register.this, Login.class);
startActivity(intent);
}
});
regBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validateUsername() && validateEmail() && validatePhoneNo() && validateUserType() && validatePassword() == true) {
Intent intent = new Intent(Register.this, Login.class);
startActivity(intent);
} else {
validateUsername();
validateEmail();
validatePhoneNo();
validateUserType();
validatePassword();
}
fAuth.createUserWithEmailAndPassword(email.getEditText().getText().toString(), password.getEditText().getText().toString()).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
FirebaseUser user = fAuth.getCurrentUser();
Toast.makeText(Register.this, "Account Created", Toast.LENGTH_SHORT).show();
DocumentReference df = fStore.collection("Users").document(user.getUid());
Map<String, Object> userInfo = new HashMap<>();
userInfo.put("Username", username.getEditText().getText().toString());
userInfo.put("Email", email.getEditText().getText().toString());
userInfo.put("phoneNo", PhoneNo.getEditText().getText().toString());
userInfo.put("Password",password.getEditText().getText().toString());
//specify the user is elderly
if (selectedElderly.isChecked()) {
userInfo.put("isElderly", "1");
}
if (selectedGuardian.isChecked()) {
userInfo.put("isGuardian", "1");
}
df.set(userInfo);
if (selectedElderly.isChecked()) {
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
if (selectedGuardian.isChecked()) {
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Register.this, "Failed to Create Account", Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
My database structure is:
database structure
As in the image, how to add one more field that contains auto-generated uid by the firebase?
If you want to add a generated id to the document, then you can do:
String id = fStore.collection("Users").document().getId();
This will generate a random id, then you can do:
DocumentReference df = fStore.collection("Users").document(user.getUid());
Map<String, Object> userInfo = new HashMap<>();
userInfo.put("Username", username.getEditText().getText().toString());
userInfo.put("Email", email.getEditText().getText().toString());
userInfo.put("phoneNo", PhoneNo.getEditText().getText().toString());
userInfo.put("Password",password.getEditText().getText().toString());
userInfo.put("id",id);
df.set(userInfo);

How to Get String Value to Another Class in Andriod?

I have created a signup form linked with Firebase. Onclick Signup button generated an unique id which I have later stored in
String str = userid;
But now I want to pass this String str value back into my main activity so that I can get that unique id and can later on use in my other code.
I have tried many methods like bundle and passing string through intent but I'm getting nothing. Please help me resolving this issue.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
btnSignIn = (Button) findViewById(R.id.sign_in_button);
btnSignUp = (Button) findViewById(R.id.sign_up_button);
inputName = (EditText) findViewById(R.id.name);
inputEmail = (EditText) findViewById(R.id.email);
inputNumber = (EditText) findViewById(R.id.number);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnResetPassword = (Button) findViewById(R.id.btn_reset_password);
btnResetPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(SignupActivity.this, ResetPasswordActivity.class));
}
});
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("users");
final String userid = reference.push().getKey();
final String name = inputName.getText().toString().trim();
final String email = inputEmail.getText().toString().trim();
final String Number = inputNumber.getText().toString().trim();
final String password = inputPassword.getText().toString().trim();
if (TextUtils.isEmpty(name)) {
Toast.makeText(getApplicationContext(), "Enter your name!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(Number)) {
Toast.makeText(getApplicationContext(), "Enter mobile number!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
if (password.length() < 6) {
Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show();
return;
}
final UserHelperClass helperClass = new UserHelperClass(name, email,Number,password,userid);
progressBar.setVisibility(View.VISIBLE);
//create user
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignupActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(SignupActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Toast.makeText(SignupActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
String str = userid;
reference.child(userid).setValue(helperClass);
startActivity(new Intent(SignupActivity.this, Home.class));
finish();
}
}
});
}
});
}
You can use SharedPreferences API to save this string to an XML file in the second activity and read it from the same XML file in the MainActivity.
To save the string:
SharedPreferences sharedPreferences = getSharedPreferences("shared_pref", 0);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString("key", userid);
editor.apply();
To retrieve the string:
SharedPreferences sharedPreferences = getSharedPreferences("shared_pref", 0);
String userid = sharePreferences.getString("key", "NOT FOUND");
You can read more about SharedPreferences here
You can start your second activity saying startActivityForResult
(See here), this way you can pass strings, numbers... back to the MainActivity from where you started your second activity once your second activity finishes.
Like
First Activity:
Intent i = new Intent(getApplicationContext(), yourSecondActivity.class);
i.putExtra("name", "value");
startActivityForResult(i, requestCode);
Second activiy:
Intent output = new Intent();
output.putExtra("name", "value");
setResult(RESULT_OK, output);
finish();
To recieve output in first Activity
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
String value = data.getStringExtra("name");

How to implement my code to send password reset link? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm making a shopping App and I've almost finished the App. But I wanted to add the Forget password feature after all. I could've done it using FirebaseAuth but for registration and login, I haven't used FirebaseAuth.
My user details are going straight to the firebase database and are being saved in the Users table. Since I'm new to android app developing I don't know how to implement my app with forget password feature.
This is my database structure :
This is my RegisterActivity:
public class RegisterActivity extends AppCompatActivity {
private Button CreateAccountButton;
private EditText InputUsername, InputPhoneNumber, InputPassword, InputRePassword, InputEmail, InputName;
private ProgressDialog loadingBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
CreateAccountButton = (Button) findViewById(R.id.register_btn);
InputUsername = (EditText) findViewById(R.id.register_username);
InputPhoneNumber = (EditText) findViewById(R.id.register_Number);
InputPassword = (EditText) findViewById(R.id.register_password);
InputRePassword = (EditText) findViewById(R.id.register_repassword);
InputEmail = (EditText) findViewById(R.id.register_email);
InputName = (EditText) findViewById(R.id.register_name);
loadingBar = new ProgressDialog(this);
CreateAccountButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CreateAccount();
}
});
}
private void CreateAccount() {
String name = InputName.getText().toString();
String username = InputUsername.getText().toString();
String phone = InputPhoneNumber.getText().toString();
String password = InputPassword.getText().toString();
String repassword = InputRePassword.getText().toString();
String email = InputEmail.getText().toString();
if (TextUtils.isEmpty(name)) {
Toast.makeText(this, "Please enter your Name", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(username)) {
Toast.makeText(this, "Please enter your Username", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(phone)) {
Toast.makeText(this, "Please enter your Phone Number", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "Please enter your Password", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(repassword)) {
Toast.makeText(this, "Please re-enter your Password", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(email)) {
Toast.makeText(this, "Please enter your Email", Toast.LENGTH_SHORT).show();
} else {
loadingBar.setTitle("Creating Account");
loadingBar.setMessage("Please wait.");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
ValidatephoneNumber(username, name, phone, password, repassword, email);
}
}
private void ValidatephoneNumber(final String username, final String name, final String phone, final String password, final String repassword, final String email)
{
final DatabaseReference RootRef;
RootRef = FirebaseDatabase.getInstance().getReference();
RootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if(!(dataSnapshot.child("Users").child(username).exists()))
{
HashMap<String, Object> userdataMap = new HashMap<>();
userdataMap.put("username", username);
userdataMap.put("name", name);
userdataMap.put("phone", phone);
userdataMap.put("password", password);
userdataMap.put("email", email);
RootRef.child("Users").child(username).updateChildren(userdataMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Toast.makeText(RegisterActivity.this, "Your account has been created!", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
}
else
{
loadingBar.dismiss();
Toast.makeText(RegisterActivity.this, "Connection Error. Please try again.", Toast.LENGTH_SHORT).show();
}
}
});
}
else
{
Toast.makeText(RegisterActivity.this,"This Username already exists! Try another Username", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
startActivity(intent);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
}
}
And here's my LoginActivity:
public class LoginActivity extends AppCompatActivity {
private EditText InputUsername, InputPassword;
private Button LoginButton;
private ProgressDialog loadingBar;
private String parentDbName = "Users";
private CheckBox chkBoxRememberMe;
private TextView AdminLink, UserLink, ForgetPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
LoginButton = (Button) findViewById(R.id.main_login_btn);
InputUsername = (EditText) findViewById(R.id.login_username);
InputPassword = (EditText) findViewById(R.id.password);
AdminLink = (TextView) findViewById(R.id.adminPanel);
UserLink = (TextView) findViewById(R.id.userLogin);
loadingBar = new ProgressDialog(this);
chkBoxRememberMe = (CheckBox) findViewById(R.id.remember_me_chkb);
ForgetPassword = (TextView) findViewById(R.id.forgetPassword);
Paper.init(this);
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
LoginUser();
}
});
AdminLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
LoginButton.setText("Login Admin");
AdminLink.setVisibility(View.INVISIBLE);
UserLink.setVisibility(View.VISIBLE);
parentDbName = "Admins";
}
});
UserLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
LoginButton.setText("Login");
AdminLink.setVisibility(View.VISIBLE);
UserLink.setVisibility(View.INVISIBLE);
parentDbName = "Users";
}
});
ForgetPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ForgotPassowrdActivity.class));
}
});
}
private void LoginUser() {
String username = InputUsername.getText().toString();
String password = InputPassword.getText().toString();
if (TextUtils.isEmpty(username))
{
Toast.makeText(this, "Please enter your Username", Toast.LENGTH_SHORT).show();
}
else if (TextUtils.isEmpty(password))
{
Toast.makeText(this, "Please enter your Password", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.setTitle("Logging in to the Account");
loadingBar.setMessage("Please wait.");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
AllowAccessToAccount(username, password);
}
}
private void AllowAccessToAccount(final String username, final String password)
{
if(chkBoxRememberMe.isChecked())
{
Paper.book().write(Prevelant.userUsernameKey, username);
Paper.book().write(Prevelant.userPasswordKey,password);
}
final DatabaseReference RootRef;
RootRef = FirebaseDatabase.getInstance().getReference();
RootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if (dataSnapshot.child(parentDbName).child(username).exists())
{
Users usersData = dataSnapshot.child(parentDbName).child(username).getValue(Users.class);
if(usersData.getUsername().equals(username))
{
if(usersData.getPassword().equals(password))
{
if(parentDbName.equals("Admins"))
{
Toast.makeText(LoginActivity.this, "Welcome Admin, You've logged in successfully!", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Intent intent = new Intent(LoginActivity.this, AdminCategoryActivity.class);
startActivity(intent);
}
else if(parentDbName.equals("Users"))
{
Toast.makeText(LoginActivity.this, "Logged in successfully!", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
Prevelant.currentOnlineUser = usersData;
startActivity(intent);
}
}
else
{
Toast.makeText(LoginActivity.this, "This Password is incorrect!", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
}
else
{
Toast.makeText(LoginActivity.this, "This Username is not registered!", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
}
}
Can I please know how to implement my code for forget password feature? I really appreciate your help!
This comes inbuilt with firebase:
FirebaseAuth.getInstance().sendPasswordResetEmail("user#example.com")

I want to retrieve current logged in user data from firestore but it shows blank where I want to show my data

I am trying to get the current logged in user from the google firestore database
and i saw this same problem in stackoverflow of a user and i used that same method but showing blank in place user details.
Please help me Thanks.
I am earlier using querysnapshot as it gives all the users.
image description here
the image for database is
enter image description here
The code is:
public class UserProfile extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int GALLERY_INTENT = 2;
private static final String TAG = "UserProfile";
String UserId;
FirebaseAuth auth;
ImageButton Photo;
ImageView photoview;
TextView name, email, password, phone;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
if(getSupportActionBar()!=null ){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
DatabaseReference Database = FirebaseDatabase.getInstance().getReference("users");
DatabaseReference DBRef = Database.child("users");
auth = FirebaseAuth.getInstance();
UserId = auth.getCurrentUser().getUid();
FirebaseFirestore mFirestore = FirebaseFirestore.getInstance();
StorageReference mStorage = FirebaseStorage.getInstance().getReference();
FirebaseStorage storage = FirebaseStorage.getInstance();
photoview = (ImageView)findViewById(R.id.photoview);
Photo = (ImageButton)findViewById(R.id.Photoedit);
name = (TextView)findViewById(R.id.username);
email = (TextView)findViewById(R.id.useremail);
password = (TextView)findViewById(R.id.password1);
phone = (TextView)findViewById(R.id.userPhone);
mFirestore.collection("users").document(UserId).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
String Name = documentSnapshot.getString("Name");
String Email = documentSnapshot.getString("Email");
String Password = documentSnapshot.getString("Password");
String Phone = documentSnapshot.getString("Phone Number");
name.setText(Name);
email.setText(Email);
password.setText(Password);
phone.setText(Phone);
}
});
Photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(UserProfile.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, GALLERY_INTENT);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap photo = (Bitmap) extras.get("data");
photoview.setImageBitmap(photo);
} else if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image ", picturePath + "");
photoview.setImageBitmap(thumbnail);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home) {
Intent i = new Intent(UserProfile.this,category.class);
startActivity(i);
finish();
}
return super.onOptionsItemSelected(item);
}
}
My database structure is
Ramiki(my app name)
So here it is
Ramiki --> users(collection)--> SiQEIDaQJfUBqZBBt1eo(document uid)----> fields(Email, Name, Password, Phone Number).
Well sorry i am not able to give screenshort because i am not allowed by stack overflow 10 points needed.
And my code for writing data in firestore is
public class LoginActivity extends AppCompatActivity implements View.OnClickListener,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LoginActivity";
private TextInputEditText textInputEditTextName;
private TextInputEditText textInputEditTextEmail;
private TextInputEditText textInputEditTextPassword;
private TextInputEditText textInputEditTextConfirmPassword;
private TextInputEditText textInputEditTextPhone;
private AppCompatButton appCompatButtonRegister;
private AppCompatTextView appCompatTextViewLoginLink;
private FirebaseAuth auth;
private ProgressBar progressBar;
private static final int RC_SIGN_IN = 1;
private GoogleApiClient mGoogleApiClient;
private SignInButton btnSignIn;
private FirebaseFirestore mFirebaseFirestore;
private FirebaseAuth.AuthStateListener authListener;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
mFirebaseFirestore = FirebaseFirestore.getInstance();
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
.setPersistenceEnabled(true)
.build();
mFirebaseFirestore.setFirestoreSettings(settings);
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
}
};
btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
btnSignIn.setOnClickListener(this);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// Customizing G+ button
btnSignIn.setSize(SignInButton.SIZE_STANDARD);
btnSignIn.setScopes(gso.getScopeArray());
appCompatTextViewLoginLink = (AppCompatTextView) findViewById(R.id.appCompatTextViewLoginLink);
appCompatTextViewLoginLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(LoginActivity.this, account.class);
startActivity(i);
finish();
}
});
//if the user is already logged in we will directly start the category activity
if (SavesharedPreferences.getInstance(this).isLoggedIn()) {
finish();
startActivity(new Intent(this, category.class));
finish();
return;
}
findViewById(R.id.appCompatButtonRegister).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Name = textInputEditTextName.getText().toString().trim();
String Email = textInputEditTextEmail.getText().toString().trim();
String Password = textInputEditTextPassword.getText().toString().trim();
String Phone_Number = textInputEditTextPhone.getText().toString().trim();
String ConfirmPassword = textInputEditTextConfirmPassword.getText().toString().trim();
progressBar.setVisibility(View.VISIBLE);
// Create a new user with a first and last name
Map<String, Object> user = new HashMap<>();
user.put("Name", Name);
user.put("Email", Email);
user.put("Password", Password);
user.put("Phone Number", Phone_Number);
if (TextUtils.isEmpty(Name)) {
textInputEditTextName.setError("Please enter name");
textInputEditTextName.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (TextUtils.isEmpty(Email)) {
textInputEditTextEmail.setError("Please enter your email");
textInputEditTextEmail.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
textInputEditTextEmail.setError("Email already exist");
textInputEditTextEmail.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (TextUtils.isEmpty(Password)) {
textInputEditTextPassword.setError("Enter a password");
textInputEditTextPassword.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if(Password.length() < 7){
textInputEditTextPassword.setError("Paasword must be greater than 7 digits");
textInputEditTextPassword.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (!textInputEditTextPassword.getText().toString().equals(textInputEditTextConfirmPassword.getText().toString())) {
textInputEditTextPassword.setError("Password Doesn't Match");
textInputEditTextPassword.requestFocus();
progressBar.setVisibility(View.GONE);
}
else {
// Add a new document with a generated ID
mFirebaseFirestore.collection("users")
.add(user)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
registerUser();
Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});
}
}
});
initViews();
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case R.id.btn_sign_in:
signIn();
break;
}
}
private void registerUser() {
final String Name = textInputEditTextName.getText().toString().trim();
final String Email = textInputEditTextEmail.getText().toString().trim();
final String Password = textInputEditTextPassword.getText().toString().trim();
final String Phone_Number = textInputEditTextPhone.getText().toString().trim();
final String ConfirmPassword = textInputEditTextConfirmPassword.getText().toString().trim();
//first we will do the validations
if (TextUtils.isEmpty(Name)) {
textInputEditTextName.setError("Please enter name");
textInputEditTextName.requestFocus();
return;
}
if (TextUtils.isEmpty(Email)) {
textInputEditTextEmail.setError("Please enter your email");
textInputEditTextEmail.requestFocus();
return;
}
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
textInputEditTextEmail.setError("Email already exist");
textInputEditTextEmail.requestFocus();
return;
}
if (TextUtils.isEmpty(Password)) {
textInputEditTextPassword.setError("Enter a password");
textInputEditTextPassword.requestFocus();
return;
}
if(Password.length() < 7 ) {
textInputEditTextPassword.setError("Paasword must be greater than 7 digits");
textInputEditTextPassword.requestFocus();
return;
}
if (TextUtils.isEmpty(ConfirmPassword)) {
textInputEditTextPassword.setError("Password Doesn't Match");
textInputEditTextPassword.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
//create user
auth.createUserWithEmailAndPassword(Email, Password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(LoginActivity.this, "Register Successful " + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()){
sendEmailVerification();
}
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
else if (!task.isSuccessful()) {
Toast.makeText(LoginActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LoginActivity.this, "Nothing Happens", Toast.LENGTH_SHORT).show();
}
}
});
}
private void sendEmailVerification() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null){
user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(LoginActivity.this,"Please Check Your Email For Verification",Toast.LENGTH_LONG).show();
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(LoginActivity.this, account.class));
finish();
}
}
});
}
}
#Override
protected void onResume() {
super.onResume();
progressBar.setVisibility(View.GONE);
}
private void initViews() {
textInputEditTextName = (TextInputEditText) findViewById(R.id.textInputEditTextName);
textInputEditTextEmail = (TextInputEditText) findViewById(R.id.textInputEditTextEmail);
textInputEditTextPassword = (TextInputEditText) findViewById(R.id.textInputEditTextPassword);
textInputEditTextPhone = (TextInputEditText) findViewById(R.id.textInputEditTextPhone);
appCompatTextViewLoginLink = (AppCompatTextView) findViewById(R.id.appCompatTextViewLoginLink);
textInputEditTextConfirmPassword = (TextInputEditText) findViewById(R.id.textInputEditTextConfirmPassword);
appCompatButtonRegister = (AppCompatButton) findViewById(R.id.appCompatButtonRegister);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(LoginActivity.this, "You Got an Error",Toast.LENGTH_LONG).show();
}
protected void onStart(){
super.onStart();
auth.addAuthStateListener(authListener);
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
auth.signInWithCredential(credential)
.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();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication Failed", Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
}
This unique id SiQEIDaQJfUBqZBBt1eo is generated when you are adding the user as a Map or when you are using a call to document() method without passing an argument.
In order to solve this, there are two ways. One would be to create a model class (UserModel), then create an object of that class and in the end get the uid of the user once it authenticated and add the object to the database like this:
String Name = textInputEditTextName.getText().toString().trim();
String Email = textInputEditTextEmail.getText().toString().trim();
String Password = textInputEditTextPassword.getText().toString().trim();
String Phone_Number = textInputEditTextPhone.getText().toString().trim();
String ConfirmPassword = textInputEditTextConfirmPassword.getText().toString().trim();
UserModel userModel = new UserModel(Name, Email, Password, Phone_Number, ConfirmPassword);
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
usersRef.document(uid).set(userModel);
See, I have passed the uid as argument to the document() method.
The second approach would be to pass no argument to the document() method but to store that key into a variable like this:
String key = usersRef.document().getKey();
usersRef.document(key).set(userModel);
Edit:
There also another method, which I recommend you use it. Instead of using this line of code:
mFirebaseFirestore.collection("users")
.add(user)
.addOnSuccessListener(/* ... */)
Use the following line of code:
mFirebaseFirestore.collection("users")
.document(uid)
.set(user)
.addOnSuccessListener(/* ... */)
Remove the old data, add fresh one and your problem will be solved.

Firebase user display name won't show on activity after creating new Firebase email password user account?

I make an sign up activity to create new user on Firebase using Simple Email Password shown below
CreateAccountActivity
public class CreateAccountActivity extends AppCompatActivity {
private ProgressDialog mprogress;
private RelativeLayout signUpactivity;
FirebaseUser user;
private Button msignUp;
public EditText mName,mEmail,mPassword,mCon_Password,mschl_name;
Spinner gender;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_creat_acc);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
mAuth = FirebaseAuth.getInstance();
mprogress = new ProgressDialog(this);
msignUp = (Button) findViewById(R.id.signUp);
signUpactivity = (RelativeLayout) findViewById(R.id.activity_signUp);
mName = (EditText) findViewById(R.id.namefield);
mEmail = (EditText) findViewById(R.id.emailField);
mPassword = (EditText) findViewById(R.id.passwordField);
mschl_name = (EditText) findViewById(R.id.sname);
String[] option = new String[]{
"Male", "Female"
};
gender = (Spinner) findViewById(R.id.gender);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, option);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
gender.setAdapter(arrayAdapter);
msignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isNetworkAvailable()){
mprogress.setMessage("Creating Account...");
mprogress.show();
mprogress.setCanceledOnTouchOutside(false);
mprogress.setCancelable(false);
createAccount();
}else{
Snackbar.make(signUpactivity, "Network UnAvailable", Snackbar.LENGTH_SHORT).show();
}
}
});
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
View focusview = null;
boolean cancel = false;
private void createAccount(){
final String name = mName.getText().toString();
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
final String gendertxt = gender.getSelectedItem().toString();
final String schl_name = mschl_name.getText().toString();
String edu_email = email+"#edutree.com";
if (isNetworkAvailable()){
mAuth.createUserWithEmailAndPassword(edu_email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(Task<AuthResult> task) {
if(task.isSuccessful()){
user = FirebaseAuth.getInstance().getCurrentUser();
String user_email = user.getEmail();
String gendertxt = gender.getSelectedItem().toString();
UserProfileChangeRequest profileChangeRequest = new UserProfileChangeRequest.Builder().setDisplayName(name).build();
user.updateProfile(profileChangeRequest).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(Task<Void> task) {
if(task.isSuccessful()){
Log.d("Profile", "User Profile Updated successfully");
FirebaseCrash.log("Profile Updated");
}else {
Log.d("Error","error while updating profile");
FirebaseCrash.log("Error while updating profile");
}
}
});
mprogress.dismiss();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(CreateAccountActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
Toast.makeText(CreateAccountActivity.this, "Welcome "+ FirebaseAuth.getInstance().getCurrentUser().getEmail(), Toast.LENGTH_LONG).show();
}
},500);
}else{
Snackbar.make(signUpactivity, "Error occurred" , Snackbar.LENGTH_SHORT).show();
mprogress.dismiss();
}
}
});
}else {
Snackbar.make(signUpactivity, "Network UnAvailable", Snackbar.LENGTH_SHORT).show();
mprogress.dismiss();
}
}
}
When user enters the information it start method CreateAccount() and then when task is successful it updates user profile and set the display name and Starts the MainActivity. but it starts the MainActivty its not showing the user name.
MainActivity
Can Anyone help me to fix this problem, and when user get sign out and sign in again then it shows the name otherwise it didn't show after Sign up.
Any Answers were highly appreciated
You need to move the code that starts MainActivity to inside the onComplete() method for the profile change. Right now your code starts the Firebase user profile change to store the display name, but it shows MainActivity before that user profile change is completed.
You can update this piece of your code, look at what I added at the end of the onComplete() method:
user.updateProfile(profileChangeRequest).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(Task<Void> task) {
if(task.isSuccessful()){
Log.d("Profile", "User Profile Updated successfully");
FirebaseCrash.log("Profile Updated");
}else {
Log.d("Error","error while updating profile");
FirebaseCrash.log("Error while updating profile");
}
mprogress.dismiss();
Intent intent = new Intent(CreateAccountActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
Toast.makeText(CreateAccountActivity.this, "Welcome "+ FirebaseAuth.getInstance().getCurrentUser().getEmail(), Toast.LENGTH_LONG).show();
}
});
Then, you can remove this code later in the function:
mprogress.dismiss();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(CreateAccountActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
Toast.makeText(CreateAccountActivity.this, "Welcome "+ FirebaseAuth.getInstance().getCurrentUser().getEmail(), Toast.LENGTH_LONG).show();
}
},500);

Categories