How to save data to same table from different activities? - java

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.

Related

Link two tables in firebase using Id in android studio using Java

have a problem, I'm working on a university project, I have two tables in firebase, the gallery table that contains the photos of the itinerary and the itinerary table that contains the various itineraries of the users now I have to make sure that the id of the itinerary and the ID of the image so as to have a photo corresponding to each itinerary ì, also created by the same user. I did so:
public void addImageItinerary() {
storageReference = FirebaseStorage.getInstance().getReference();
referenceDb = FirebaseDatabase.getInstance().getReference();
firestore = FirebaseFirestore.getInstance();
auth = FirebaseAuth.getInstance();
if (images != null) {
StorageReference itineraryRef = storageReference.child("itinerary_image/" + FirebaseAuth.getInstance().getCurrentUser().getUid() + ".jpg");
itineraryRef.putFile(images).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
itineraryRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String itineraryId = referenceDb.child("Itinerary").push().getKey();
Log.i("itineraryId", itineraryId);
HashMap<String, Object> map = new HashMap<>();
map.put("image", uri.toString());
referenceDb.child("Gallery").child(FirebaseAuth.getInstance().getCurrentUser().getUid()+ "/" + itineraryId).setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
// APRO SCHERMATA MAPPA
// openMapFragment();
Toast.makeText(insertImage_fragment.getActivity(), "ok", Toast.LENGTH_SHORT).show();
} else {
//ERRORE
Toast.makeText(insertImage_fragment.getActivity(), "Operation failed. Please try again", Toast.LENGTH_SHORT).show();
}
}
});
}
});
} else {
Toast.makeText(insertImage_fragment.getActivity(), task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
} else{
Toast.makeText(insertImage_fragment.getActivity(),"Please add image", Toast.LENGTH_SHORT).show();
}
}
enter image description here

Android firestore when users change the image, NullPointerException occurs

I'm making setup_profile activity. Users can change information.
When users do not change the image, it is good. But when the user change image errors come.
I add 'null checker' like
if (uri!=null) But I don know why it is.
Here are the errors.
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.toString()' on a null object reference
at com.razberrylovers.mbting.SetUpActivity.saveToFireStore(SetUpActivity.java:291)
at com.razberrylovers.mbting.SetUpActivity.access$700(SetUpActivity.java:40)
at com.razberrylovers.mbting.SetUpActivity$10.onComplete(SetUpActivity.java:217)
Here is my code.
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_up);
Toolbar setUpToolbar = findViewById(R.id.setup_toolbar);
setSupportActionBar(setUpToolbar);
getSupportActionBar().setTitle("Profile");
storageReference = FirebaseStorage.getInstance().getReference();
firestore = FirebaseFirestore.getInstance();
auth = FirebaseAuth.getInstance();
Uid = auth.getCurrentUser().getUid();
progressBar = findViewById(R.id.progressBar);
progressBar.setVisibility(View.INVISIBLE);
circleImageView = findViewById(R.id.circleImageView);
mProfileName = findViewById(R.id.profile_name);
mSaveBtn = findViewById(R.id.save_btn);
mProfileSchool = findViewById(R.id.profile_school);
mconcreteregion = findViewById(R.id.profile_concreteregion);
// setting dialog
textView_age=findViewById(R.id.age_dialog);
textView_age.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new FragmentDialogBox().show(getSupportFragmentManager(),"fragmentDialog");
}
});
textView_job=findViewById(R.id.job_dialog);
textView_job.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Fragment_job().show(getSupportFragmentManager(),"fragmentDialog");
}
});
textView_region = findViewById(R.id.region_dialog);
textView_region.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Fragment_region().show(getSupportFragmentManager(),"fragmentDialog");
}
});
textView_height = findViewById(R.id.height_dialog);
textView_height.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Fragment_height().show(getSupportFragmentManager(),"fragmentDialog");
}
});
textView_religion = findViewById(R.id.religion_dialog);
textView_religion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Fragment_religion().show(getSupportFragmentManager(),"fragmentDialog");
}
});
textView_drink = findViewById(R.id.drink_dialog);
textView_drink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Fragment_drink().show(getSupportFragmentManager(),"fragmentDialog");
}
});
textView_smoke = findViewById(R.id.smoke_dialog);
textView_smoke.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Fragment_smoke().show(getSupportFragmentManager(),"fragmentDialog");
}
});
textView_mbti = findViewById(R.id.mbti_dialog);
textView_mbti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Fragment_mbti().show(getSupportFragmentManager(),"fragmentDialog");
}
});
and load data from firestore + mSaveBtn click listener(including the case of not changing the picture)
firestore.collection("Users").document(Uid).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
if (task.getResult().exists()){
String name = task.getResult().getString("name");
String age = task.getResult().getString("age");
String job = task.getResult().getString("job");
String imageUrl = task.getResult().getString("image");
String school = task.getResult().getString("school");
String region = task.getResult().getString("region");
String concrete_region = task.getResult().getString("concrete_region");
String height = task.getResult().getString("height");
String religion = task.getResult().getString("religion");
String drink = task.getResult().getString("drink");
String smoke = task.getResult().getString("smoke");
String mbti = task.getResult().getString("mbti");
mProfileName.setText(name);
textView_age.setText(age);
textView_job.setText(job);
mProfileSchool.setText(school);
textView_region.setText(region);
mconcreteregion.setText(concrete_region);
textView_height.setText(height);
textView_religion.setText(religion);
mImageUri = Uri.parse(imageUrl);
textView_drink.setText(drink);
textView_smoke.setText(smoke);
textView_mbti.setText(mbti);
Glide.with(SetUpActivity.this).load(imageUrl).into(circleImageView);
}
}
}
});
//
mSaveBtn.setOnClickListener(v -> {
progressBar.setVisibility(View.VISIBLE);
String name = mProfileName.getText().toString();
String age = textView_age.getText().toString();
String job = textView_job.getText().toString();
String school = mProfileSchool.getText().toString();
String region = textView_region.getText().toString();
String concrete_region = mconcreteregion.getText().toString();
String height = textView_height.getText().toString();
String religion = textView_religion.getText().toString();
String drink = textView_drink.getText().toString();
String smoke = textView_smoke.getText().toString();
String mbti = textView_mbti.getText().toString();
StorageReference imageRef = storageReference.child("Profile_pics").child(Uid+".jpg");
//프로필 수정시 사진을 바꾸지 않았을 경우를 해결
if(isPhotoSelected)
{
if (!name.isEmpty() && mImageUri != null) {
imageRef.putFile(mImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
saveToFireStore(task, name, age, job, school, region,
concrete_region, height, religion, drink, smoke, mbti, imageRef);
} else {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(SetUpActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
} else {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(SetUpActivity.this, "등록을 하지 않은 것이 있습니다.", Toast.LENGTH_SHORT).show();
}
}
else{
saveToFireStore(null, name, age, job, school, region,
concrete_region, height, religion, drink, smoke, mbti, imageRef);
}
});
--> also code
Next code
There is a section that allows permission, and there is a saveToFireStore() method.-> when the task is null, the photo is not changed and when the task is not null photo will be changed.
circleImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(ContextCompat.checkSelfPermission(SetUpActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(SetUpActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
else{
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(SetUpActivity.this);
}
}
}
});
}
private void saveToFireStore(Task<UploadTask.TaskSnapshot> task, String name,
String age, String job, String school, String region,
String concrete_region, String height, String religion,
String drink, String smoke, String mbti,
StorageReference imageRef) {
if(task != null){
imageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
downloadUri = uri;
}
});
}
else{
downloadUri = mImageUri;
}
HashMap<String , Object> map = new HashMap<>();
map.put("name", name);
map.put("age", age);
map.put("job", job);
map.put("school", school);
map.put("region", region);
map.put("concrete_region", concrete_region);
map.put("height", height);
map.put("religion", religion);
map.put("drink", drink);
map.put("smoke", smoke);
map.put("mbti", mbti);
map.put("image",downloadUri.toString());
firestore.collection("Users").document(Uid).set(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(SetUpActivity.this, "프로필이 등록되었습니다.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(SetUpActivity.this, MainActivity.class));
finish();
}
else{
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(SetUpActivity.this,task.getException().toString(),Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE){
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK){
mImageUri = result.getUri();
circleImageView.setImageURI(mImageUri);
isPhotoSelected = true;
}
else if(resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE){
Toast.makeText(this,result.getError().getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
The part of the error that logcat showed
imageRef.putFile(mImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
saveToFireStore(task, name, age, job, school, region,
concrete_region, height, religion, drink, smoke, mbti, imageRef);
} else {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(SetUpActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
and
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(SetUpActivity.this, "프로필이 등록되었습니다.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(SetUpActivity.this, MainActivity.class));
finish();
}
else{
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(SetUpActivity.this,task.getException().toString(),Toast.LENGTH_SHORT).show();
}
}

How do i get an OTP the second time after I've logged out the first time?

After I log in the first time and log out, the next time I log in I don't get an OTP.
How do I solve this problem??
The code works fine if I enter the phone number for the first time. Second time onwards I am not getting OTP number. In order to get the OTP number, I need to restart my phone each time. If I close and reopen the app then it's not helping me too.
VerifyPhoneActivity
public class VerifyPhoneActivity extends AppCompatActivity {
private String verificationId;
private FirebaseAuth mAuth;
private ProgressBar progressBar;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verify_phone);
mAuth = FirebaseAuth.getInstance();
editText = findViewById(R.id.editTextCode);
progressBar =findViewById(R.id.progressbar);
String phonenumber = getIntent().getStringExtra("phonenumber");
setVerificationCode(phonenumber);
findViewById(R.id.buttonSignIn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String code = editText.getText().toString().trim();
if(code.isEmpty() || code.length()< 6){
editText.setError("Enter code");
editText.requestFocus();
return;
}
verifyCode(code);
}
});
}
private void verifyCode(String code){
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
SignInWithCredential(credential);
}
private void SignInWithCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Intent intent = new Intent(VerifyPhoneActivity.this, ProfileActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}else {
Toast.makeText(VerifyPhoneActivity.this, task.getException().getMessage(),Toast.LENGTH_LONG).show();
}
}
});
}
private void setVerificationCode(String number){
progressBar.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,
mCallBack
);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks
mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
}
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code =phoneAuthCredential.getSmsCode();
if(code != null){
editText.setText(code);
SignInWithCredential(phoneAuthCredential);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(VerifyPhoneActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
};
You should read docs if mobile gets registered on firebase it won't send OTP all time, maybe few times.
Once mobile is registered you will get success and then you can verify.

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

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.

Categories